A REST API in Go with net/http alone, no framework

The first question anyone starting Go asks is "gin, echo or chi?". My answer: most APIs need none of them. Since Go 1.22 the standard library's router in net/http understands the HTTP method and path parameters, and everything else a REST API needs was already in Go.
I wrote the SimaCMS backend in Go on this same net/http, with no framework. The migration story is in moving from Laravel to Go. Here we build a small task API step by step.
Routing with net/http: method and parameter in the pattern
In Go 1.22 a ServeMux pattern can start with a method and capture a path segment with {id}:
mux := http.NewServeMux()
mux.HandleFunc("GET /api/tasks", s.list)
mux.HandleFunc("POST /api/tasks", s.create)
mux.HandleFunc("GET /api/tasks/{id}", s.show)
mux.HandleFunc("DELETE /api/tasks/{id}", s.remove)
Two things come free: a request with the wrong method (say PUT) gets a 405 with an Allow header, and a GET pattern also answers HEAD. The full story is on the Go blog.

Reading the parameter and returning JSON
You read {id} with r.PathValue("id"). A small helper is all you need to write JSON:
func (s *store) show(w http.ResponseWriter, r *http.Request) {
id, err := strconv.Atoi(r.PathValue("id"))
if err != nil {
writeError(w, http.StatusBadRequest, "id must be a number")
return
}
s.mu.Lock()
t, ok := s.tasks[id]
s.mu.Unlock()
if !ok {
writeError(w, http.StatusNotFound, "task not found")
return
}
writeJSON(w, http.StatusOK, t)
}
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
json.NewEncoder(w).Encode(v)
}
func writeError(w http.ResponseWriter, status int, msg string) {
writeJSON(w, status, map[string]string{"error": msg})
}
Order matters: headers are set before WriteHeader; any header change after it is ignored.
Reading the body, with a cap and strictness
Most first APIs break on reading the body. Two extra lines prevent two problems: MaxBytesReader stops anyone sending a multi-gigabyte body, and DisallowUnknownFields rejects a mistyped field instead of silently ignoring it:
func (s *store) create(w http.ResponseWriter, r *http.Request) {
var in struct {
Title string `json:"title"`
}
r.Body = http.MaxBytesReader(w, r.Body, 1<<20) // 1 MB
dec := json.NewDecoder(r.Body)
dec.DisallowUnknownFields()
if err := dec.Decode(&in); err != nil || in.Title == "" {
writeError(w, http.StatusBadRequest, `send {"title": "..."}`)
return
}
s.mu.Lock()
s.nextID++
t := task{ID: s.nextID, Title: in.Title}
s.tasks[t.ID] = t
s.mu.Unlock()
writeJSON(w, http.StatusCreated, t)
}
The data lives in a map guarded by a sync.Mutex. Every handler runs in its own goroutine, so without the lock two concurrent requests corrupt the map. In a real project this is your database.
Middleware is a function that takes a handler
In net/http, middleware is just a function that takes an http.Handler and returns another. Logging every request with log/slog:
func logRequests(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
next.ServeHTTP(w, r)
slog.Info("request", "method", r.Method, "path", r.URL.Path, "took", time.Since(start))
})
}
Authentication, CORS and rate limiting have the same shape and wrap each other: logRequests(auth(mux)).
A server with timeouts and a clean shutdown
http.ListenAndServe(":8080", mux) is fine for an example but not for a real server: it has no timeouts, so a slow client can hold a connection open forever. Build an http.Server with timeouts, and when a stop signal arrives (during a Docker deploy, say) let in-flight requests finish:
srv := &http.Server{
Addr: ":8080",
Handler: logRequests(mux),
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 10 * time.Second,
WriteTimeout: 30 * time.Second,
IdleTimeout: 60 * time.Second,
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
go func() {
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
slog.Error("server", "err", err)
os.Exit(1)
}
}()
<-ctx.Done()
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
srv.Shutdown(shutdownCtx)
If the service runs in a container, also see GOMAXPROCS in Docker.
Tests, still without a library
The net/http/httptest package builds a request and a response recorder without starting a server:
func TestCreateTask(t *testing.T) {
s := &store{tasks: map[int]task{}}
req := httptest.NewRequest("POST", "/api/tasks", strings.NewReader(`{"title":"write the post"}`))
rec := httptest.NewRecorder()
s.create(rec, req)
if rec.Code != http.StatusCreated {
t.Fatalf("got %d, want 201: %s", rec.Code, rec.Body)
}
}
So when is a framework worth it?
net/http is not everything. If you want OpenAPI docs generated from code, have complex validation across dozens of endpoints, or your team is already at home in gin, a library earns its weight. But start with net/http, and add a library when you actually miss something, not on day one.
All the code in this tutorial together is a program of about 130 lines that runs with go run . and has no outside dependencies.
Comments
Sign in to leave a comment.
Sign inLoading…



