← कोर्स पर वापस जाएँ: Go from scratch

Final project: REST tasks API with tests

वीडियो जल्द आ रहा है

You have reached the last lesson. In eight weeks you went from installing Go to launching goroutines, and now you will bring everything together in a real project: a complete REST tasks API, with concurrency-safe storage, JSON responses, correct status codes, automated tests and a graceful shutdown. The previous lesson gave you listing, creating and reading a task; here you add updating and deleting, write the tests and close the server with a context. There is no single solution: what matters is that you meet the requirements and that your code is clear.

Brief and requirements

  • Your own Go module (go mod init tasksapi) with Go 1.22 or later.
  • Task model with id, title, done and created_at (time.Time).
  • Routes: GET /tasks, POST /tasks, GET /tasks/{id}, PATCH /tasks/{id} (changes title and/or done), DELETE /tasks/{id}.
  • Optional filter GET /tasks?done=true returns only completed tasks.
  • Codes: 200, 201 when creating, 204 when deleting, 400 for invalid input, 404 if missing, 405 for a wrong method.
  • The store lives in its own package or file, protected with sync.Mutex, knowing nothing about HTTP.
  • On Ctrl+C, the server shuts down with http.Server.Shutdown and a context with a 5 second deadline.
  • Tests with httptest that cover every error case, and go test -race with no warnings.

Suggested steps

Work in small stages and run go test after each one. First create the module and copy the store from the previous lesson, adding the CreatedAt field and the Update and Delete methods. Second, write the store tests without HTTP. Third, add the handlers one by one, each with its test. Fourth, write main with the graceful shutdown. Finally, test by hand with curl and run go vet and go test -race. If something fails, read the compiler message calmly: it almost always says exactly which line and which type do not match.

bash
mkdir tasksapi && cd tasksapi
go mod init tasksapi
# files: main.go (server + shutdown), api.go (handlers), store.go (data),
#        api_test.go, store_test.go
go vet ./...
go test -race ./...
go run .

Key pieces

For PATCH, the trick is to tell an absent field from a field with a zero value: if the client sends only {"done":true}, you must not erase the title. Use pointers in the input struct: a nil pointer means "it did not come". The store's Update method receives those pointers and only changes what is not nil. For the shutdown, run ListenAndServe in a goroutine and wait for the signal with signal.NotifyContext; then call srv.Shutdown with a context with a deadline. Note that ListenAndServe returns http.ErrServerClosed on a normal shutdown, and that is not an error.

go
// store.go (fragment): Update only touches the fields that came in the request.
func (s *Store) Update(id int, title *string, done *bool) (Task, bool) {
	s.mu.Lock()
	defer s.mu.Unlock()
	t, ok := s.tasks[id]
	if !ok {
		return Task{}, false
	}
	if title != nil {
		t.Title = *title
	}
	if done != nil {
		t.Done = *done
	}
	s.tasks[id] = t
	return t, true
}

// api.go (fragment): PATCH /tasks/{id}
func (a *API) update(w http.ResponseWriter, r *http.Request) {
	id, err := strconv.Atoi(r.PathValue("id"))
	if err != nil {
		http.Error(w, "invalid id", http.StatusBadRequest)
		return
	}
	var in struct {
		Title *string `json:"title"`
		Done  *bool   `json:"done"`
	}
	if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
		http.Error(w, "invalid JSON", http.StatusBadRequest)
		return
	}
	if in.Title != nil && *in.Title == "" {
		http.Error(w, "title cannot be empty", http.StatusBadRequest)
		return
	}
	t, ok := a.store.Update(id, in.Title, in.Done)
	if !ok {
		http.Error(w, "task not found", http.StatusNotFound)
		return
	}
	writeJSON(w, http.StatusOK, t)
}

// main.go (fragment): graceful shutdown on Ctrl+C.
func main() {
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
	defer stop()

	srv := &http.Server{Addr: ":8080", Handler: newMux(&API{store: NewStore()})}
	go func() {
		if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
			log.Fatal(err)
		}
	}()

	<-ctx.Done() // wait for Ctrl+C
	shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := srv.Shutdown(shutdownCtx); err != nil {
		log.Println("shutdown:", err)
	}
}

How to test it

A good suite combines a happy-path test with a table for the errors. The doRequest helper avoids repeating the httptest code, and t.Helper() makes failures point at the test line and not the helper's. Each test creates its own store so they do not depend on each other: that way order does not matter and you can run them in parallel. Complete the table yourself with more cases (negative id, empty title, deleting twice, filter done=true) until you cover every 4xx response.

go
package main

import (
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
)

func doRequest(t *testing.T, h http.Handler, method, path, body string) *httptest.ResponseRecorder {
	t.Helper()
	req := httptest.NewRequest(method, path, strings.NewReader(body))
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, req)
	return rec
}

func TestCreateAndGet(t *testing.T) {
	h := newMux(&API{store: NewStore()})

	rec := doRequest(t, h, http.MethodPost, "/tasks", `{"title":"Buy milk"}`)
	if rec.Code != http.StatusCreated {
		t.Fatalf("create status = %d; want 201", rec.Code)
	}
	var created Task
	if err := json.NewDecoder(rec.Body).Decode(&created); err != nil {
		t.Fatal(err)
	}
	if created.ID != 1 || created.Title != "Buy milk" || created.Done {
		t.Errorf("unexpected task: %+v", created)
	}

	rec = doRequest(t, h, http.MethodGet, "/tasks/1", "")
	if rec.Code != http.StatusOK {
		t.Errorf("get status = %d; want 200", rec.Code)
	}
}

func TestErrors(t *testing.T) {
	tests := []struct {
		name   string
		method string
		path   string
		body   string
		want   int
	}{
		{"unknown id", http.MethodGet, "/tasks/99", "", http.StatusNotFound},
		{"bad id", http.MethodGet, "/tasks/abc", "", http.StatusBadRequest},
		{"empty title", http.MethodPost, "/tasks", `{"title":""}`, http.StatusBadRequest},
		{"bad json", http.MethodPost, "/tasks", "not json", http.StatusBadRequest},
		{"wrong method", http.MethodPut, "/tasks", "", http.StatusMethodNotAllowed},
	}
	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			h := newMux(&API{store: NewStore()})
			rec := doRequest(t, h, tc.method, tc.path, tc.body)
			if rec.Code != tc.want {
				t.Errorf("status = %d; want %d", rec.Code, tc.want)
			}
		})
	}
}

Completion criteria

  • go vet ./... and gofmt -l . print nothing.
  • go test -race ./... passes green.
  • The five routes work with curl and return the codes in the brief.
  • An empty list answers [] and never null.
  • Ctrl+C ends the server without error and without cutting a request in progress.
  • You can explain in your own words why the store needs a Mutex and what the context is for.

जो सीखा उसे परखें

प्रश्न 1 / 8

What is the go mod init command for?

✎ मेरे नोट्स

केवल इस ब्राउज़र में सहेजा गया। खाते में रखने के लिए साइन इन करें।0/5000 अक्षर

← पिछला