← Project templates

WEB AND APIS · IN THE APP NOW

net/http JSON API

A notes API on the standard library alone. Since Go 1.22, http.ServeMux understands methods and wildcards, so a route such as "GET /notes/{id}" needs no router package.

Offline: standard library only

Open it in the browser Playground →

What it is

It builds and runs offline. main replays requests through the mux with httptest, because the sandbox has no sockets. The test checks each status, including the 405 Method Not Allowed the mux returns for a method no pattern registered.

Every template's Go program was compiled for GOOS=wasip1 GOARCH=wasm with Go 1.27, then run, vetted and tested before it was added to the app.

Files

text
http-api/
├── go.mod
├── main.go
├── server.go
└── server_test.go

The code

server.go

go
// newServer uses the method and wildcard patterns net/http has understood
// since Go 1.22: no router dependency at all.
func newServer() http.Handler {
	store := &notes{next: 1, byID: map[int]Note{}}
	mux := http.NewServeMux()
	mux.HandleFunc("GET /notes", store.list)
	mux.HandleFunc("POST /notes", store.create)
	mux.HandleFunc("GET /notes/{id}", store.get)
	mux.HandleFunc("DELETE /notes/{id}", store.remove)
	return mux
}

server.go

go
func (s *notes) get(w http.ResponseWriter, r *http.Request) {
	id, err := strconv.Atoi(r.PathValue("id"))
	if err != nil {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": "id must be a number"})
		return
	}
	s.mu.Lock()
	defer s.mu.Unlock()
	note, ok := s.byID[id]
	if !ok {
		writeJSON(w, http.StatusNotFound, map[string]string{"error": "no such note"})
		return
	}
	writeJSON(w, http.StatusOK, note)
}

server_test.go

go
package main

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

func TestNotes(t *testing.T) {
	server := newServer()
	steps := []struct {
		method, path, body string
		want               int
	}{
		{"POST", "/notes", `{"text":"hello"}`, http.StatusCreated},
		{"POST", "/notes", `{}`, http.StatusBadRequest},
		{"GET", "/notes/1", "", http.StatusOK},
		{"GET", "/notes/9", "", http.StatusNotFound},
		{"PATCH", "/notes/1", "", http.StatusMethodNotAllowed},
	}
	for _, step := range steps {
		recorder := httptest.NewRecorder()
		server.ServeHTTP(recorder, httptest.NewRequest(step.method, step.path, strings.NewReader(step.body)))
		if recorder.Code != step.want {
			t.Errorf("%s %s = %d, want %d", step.method, step.path, recorder.Code, step.want)
		}
	}
}

What you learn

  • Register method and wildcard patterns with http.NewServeMux and HandleFunc.
  • Read a wildcard with r.PathValue and convert it with strconv.Atoi.
  • Decode bounded JSON input with http.MaxBytesReader and json.NewDecoder.
  • Write JSON with a status code through one small helper.
  • Let the mux answer 404 and 405 for routes and methods you did not register.

Run it on a server

Replace the request loop in main with http.ListenAndServe, import log and net/http, and drop the imports main no longer uses.

go
func main() {
	log.Fatal(http.ListenAndServe(":8080", newServer()))
}
bash
go test ./...
go run .
curl -X POST localhost:8080/notes -d '{"text":"buy coffee"}'
curl localhost:8080/notes/1

Related: http.Handler is one method, like Reader · An HTTP request has a lifecycle and a budget · Go services