My account

HTTP services in Go

The net/http package is enough to build a real API. If you understand handlers and the Go 1.22 routing, middleware, one goroutine per request, server and client timeouts, safe JSON reading, graceful shutdown in Kubernetes and the database connection pool, you can answer most interview questions.

Not reviewedWritten with AI helpReading time: 22 minOnline shop exampleGo 1.25 code

Author: bezzad

Contents

The problem: an order API that breaks under load

The order API of our shop works well in tests. But in production we have these reports:

  1. During a sale the last pair of shoes was sold twice.
  2. On every deploy a few dozen users get a 502 error.
  3. When the payment provider is slow, all payment requests get stuck and the service stops answering.
  4. A broken client sent a 100 MB JSON body, and the pod ran out of memory.

All of these come from a few default behaviors of net/http that you must know. In this lesson we build a small order API that is ready for production.

The Handler type

Everything in net/http is built around one small interface:

type Handler interface {
	ServeHTTP(ResponseWriter, *Request)
}
  1. Any type with a ServeHTTP method is a handler.
  2. The HandlerFunc type turns a normal function into a handler. So most of the time we just write a function.
  3. The router (ServeMux) is a handler too. Middleware is also a handler. So they can all be wrapped inside each other.

Routing with ServeMux

Since Go 1.22 the standard router understands the HTTP method and path variables. For most APIs you do not need a router library anymore:

func (a *API) Routes() http.Handler {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /orders/{id}", a.getOrder)
	mux.HandleFunc("POST /orders", a.createOrder)
	mux.HandleFunc("GET /healthz", a.healthz)
	return RequestID(Logging(a.log, Recover(a.log, mux)))
}

func (a *API) getOrder(w http.ResponseWriter,
	r *http.Request) {
	id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
	if err != nil {
		http.Error(w, "bad order id", http.StatusBadRequest)
		return
	}
	o, err := a.store.Order(r.Context(), id)
	if errors.Is(err, ErrNotFound) {
		http.Error(w, "order not found", http.StatusNotFound)
		return
	}
	if err != nil {
		a.log.Error("get order", "id", id, "err", err)
		http.Error(w, "server error",
			http.StatusInternalServerError)
		return
	}
	writeJSON(w, http.StatusOK, o)
}
  1. The order pattern with GET only matches GET requests. For another method, the router returns 405 by itself.
  2. The PathValue method returns the value of a path variable. Always check it, because it comes from the user.
  3. When two patterns match one path, the more specific pattern wins.
  4. Always return after http.Error. Writing to the response again gives a “superfluous WriteHeader” warning.

The middleware chain

A middleware is a function that takes a handler and returns a new handler. It does work that all requests share, then calls the next handler:

func Logging(log *slog.Logger, next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter,
		r *http.Request) {
		start := time.Now()
		rec := &statusRecorder{ResponseWriter: w, status: 200}
		next.ServeHTTP(rec, r)
		log.Info("request", "method", r.Method,
			"path", r.URL.Path, "status", rec.status,
			"took", time.Since(start))
	})
}

// statusRecorder remembers the status code for the log.
type statusRecorder struct {
	http.ResponseWriter
	status int
}

func (s *statusRecorder) WriteHeader(code int) {
	s.status = code
	s.ResponseWriter.WriteHeader(code)
}
  1. Code before next.ServeHTTP runs on the way in, and code after it runs on the way back.
  2. The order matters. The outer layer runs first. Recover must be inside Logging, so a 500 error is logged too.
  3. Common layers: request id, logging, recover, authentication, rate limiting and CORS.
Each layer does one small job and calls the next layerRequestIDLoggingRecoverServeMuxgetOrdermakes an idtime and statuscatches panicsfinds the routereads the orderrequest goes inresponse comes backRequestID(Logging(Recover(mux)))
The request passes the request id, logging and recover layers until it reaches the router and the handler. The response goes back through the same layers.

Each request is a goroutine

The net/http server runs each connection in its own goroutine. So your handler may run thousands of times at the same moment. This is our first bug:

// Bad: a shared map changed by many goroutines
var stock = map[string]int{"shoe": 1}

func (a *API) buy(w http.ResponseWriter, r *http.Request) {
	sku := r.PathValue("sku")
	if stock[sku] > 0 {
		stock[sku]-- // two requests can both get here
	}
}
  1. Two requests read “1 left” at the same time, both pass the check, and both sell.
  2. Concurrent writes to a map can even stop the whole process with a fatal error.
  3. Anything shared between requests (handler fields, global variables, caches) must be read-only, or protected with a mutex or the sync/atomic types.
  4. The real stock must be reduced in the database with a conditional update. A mutex only works inside one pod.
request 1request 2request 3goroutine 1goroutine 2goroutine 3stock["shoe"]: 1one shared mapno lock: data racethe last shoe is sold twicewith a lock: goroutines enter one by one
Three requests in three goroutines change one shared map at the same time. Without a lock, the last shoe is sold twice.

Run your tests with the race flag. The race detector finds this kind of bug in concurrent tests.

Reading JSON safely

Our fourth bug was a huge body. Never read a request body without a limit:

func (a *API) createOrder(w http.ResponseWriter,
	r *http.Request) {
	r.Body = http.MaxBytesReader(w, r.Body, 1<<20) // 1 MB
	dec := json.NewDecoder(r.Body)
	dec.DisallowUnknownFields()
	var in NewOrder
	if err := dec.Decode(&in); err != nil {
		http.Error(w, "bad JSON", http.StatusBadRequest)
		return
	}
	if len(in.Items) == 0 {
		http.Error(w, "no items",
			http.StatusUnprocessableEntity)
		return
	}
	o, err := a.store.Create(r.Context(), in)
	if err != nil {
		http.Error(w, "server error",
			http.StatusInternalServerError)
		return
	}
	writeJSON(w, http.StatusCreated, o)
}

func writeJSON(w http.ResponseWriter, status int, v any) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(status)
	json.NewEncoder(w).Encode(v)
}
  1. The MaxBytesReader function stops reading with an error after 1 MB.
  2. The DisallowUnknownFields method rejects misspelled fields, instead of silently ignoring them.
  3. Set headers before WriteHeader. Changing a header after it has no effect.
  4. Validate the input after Decode. Valid JSON can still contain meaningless data.

Server timeouts

The http.ListenAndServe function makes a server with no timeouts at all. A slow or malicious client can keep connections open forever. Always build an http.Server with timeouts:

srv := &http.Server{
	Addr:              ":8080",
	Handler:           api.Routes(),
	ReadHeaderTimeout: 5 * time.Second,
	ReadTimeout:       10 * time.Second,
	WriteTimeout:      30 * time.Second,
	IdleTimeout:       60 * time.Second,
}
  1. ReadHeaderTimeout limits reading the headers. It stops the Slowloris attack, which sends headers very slowly.
  2. ReadTimeout limits reading the whole request, including the body.
  3. WriteTimeout limits writing the response. It must be longer than your slowest normal endpoint.
  4. IdleTimeout says how long an idle keep-alive connection stays open.

The HTTP client

Our third bug came from the client. The default http.DefaultClient also has no timeout:

// One client for the whole service, made at startup.
var payClient = &http.Client{Timeout: 10 * time.Second}

req, err := http.NewRequestWithContext(ctx, "POST", url, body)
if err != nil {
	return err
}
resp, err := payClient.Do(req)
if err != nil {
	return err
}
defer resp.Body.Close()
  1. Make one shared client and reuse it. The client keeps connections and reuses them.
  2. Build the request with a context, so a cancelled user request also stops the outside call.
  3. Always close the response body, even when the status code is an error. An unclosed body holds the connection.

The database connection pool

The sql.DB type is not one connection. It is a pool of connections, and it is safe for concurrent use. Make it once at startup and pass it everywhere:

db, err := sql.Open("pgx", os.Getenv("DATABASE_URL"))
if err != nil {
	return err
}
db.SetMaxOpenConns(20)
db.SetMaxIdleConns(20)
db.SetConnMaxLifetime(30 * time.Minute)
  1. Without SetMaxOpenConns, the number of connections has no limit. Under load you may go over the connection limit of the database.
  2. Count the limit with the number of pods. 10 pods times 20 connections is 200 database connections.
  3. Always call rows.Close. Each open rows value has borrowed one connection from the pool.

Graceful shutdown

Our second bug happened on every deploy. Kubernetes sends SIGTERM to stop a pod. If the program does not catch it, it exits at once and running requests are cut:

func run(api *API, ready *atomic.Bool) error {
	srv := newServer(api) // the http.Server with timeouts above
	ctx, stop := signal.NotifyContext(context.Background(),
		syscall.SIGTERM, os.Interrupt)
	defer stop()

	errCh := make(chan error, 1)
	go func() { errCh <- srv.ListenAndServe() }()
	ready.Store(true)

	select {
	case err := <-errCh:
		return err // could not start, e.g. port in use
	case <-ctx.Done():
	}

	ready.Store(false)          // readyz now returns 503
	time.Sleep(5 * time.Second) // let the load balancer notice
	shutCtx, cancel := context.WithTimeout(
		context.Background(), 20*time.Second)
	defer cancel()
	return srv.Shutdown(shutCtx)
}
  1. The signal.NotifyContext function gives a context that is cancelled by SIGTERM.
  2. The readyz endpoint now returns 503. Kubernetes takes the pod out of the Service endpoints.
  3. Waiting a few seconds is needed, because removing the pod from the load balancer happens at the same time as SIGTERM, with a small delay.
  4. The Shutdown method stops accepting new connections and waits until running requests finish, up to the limit of shutCtx.
  5. All the waits together must be shorter than the Kubernetes grace period (30 seconds by default). After that, Kubernetes sends SIGKILL.
Graceful shutdown in KubernetesSIGTERMsignalreadyz: 503not readysrv.Shutdownlistener closeslast request doneexitSIGKILL30-second limitnew connection refusedGreen bars: running requests finish
SIGTERM arrives, readyz returns 503, Shutdown closes the listener, running requests finish, and the program exits before the 30-second limit.
Two health endpoints The healthz endpoint (liveness) only says the process is alive. If it fails, Kubernetes restarts the pod. The readyz endpoint (readiness) says whether the pod can take traffic. Do not check the database in liveness, or a short database problem restarts all pods.

Common mistakes

Mistake Result The right way
Using http.ListenAndServe The server has no timeouts. An http.Server with ReadHeaderTimeout and the others
Using http.DefaultClient or http.Get An outside call can hang forever. One shared client with a Timeout and a context
Not closing the response body on the error path A connection leak A deferred resp.Body.Close right after Do
A shared map or variable without a lock A data race and double selling A lock, atomic, or the database
Reading the body without a limit Out of memory from one big request The MaxBytesReader function
Forgetting return after http.Error The response is written twice. Always return after writing an error.
Exiting at once on SIGTERM 502 errors on every deploy NotifyContext and Shutdown
Making an sql.DB per request Connections run out. One pool at startup

Summary in seven lines

  1. Everything in net/http is a handler: handlers, the router and middleware.
  2. Since Go 1.22 the standard router understands methods and path variables.
  3. Each request runs in its own goroutine. Protect shared data and run tests with the race flag.
  4. Read the body with a limit, validate the input, and return after writing an error.
  5. The default server and client have no timeouts. Always set them yourself.
  6. Make one sql.DB and one http.Client for the whole program, and set a connection limit.
  7. On SIGTERM, report not ready, wait a little, and shut down gracefully with Shutdown.

Done reading this lesson?Mark it as finished so it shows in your lessons list and report card.