How-To Guide

How to Build an HTTP Server in Go

Build a production-ready Go HTTP server with method routing, timeouts, structured logging, body limits, graceful shutdown, and httptest coverage.

On this page

  1. Introduction
  2. Create a testable mux
  3. Add request logging and body limits
  4. Configure server timeouts
  5. Shut down gracefully
  6. Test handlers without a live server
  7. Common pitfalls
  8. Conclusion

Introduction

Go’s net/http package is a complete HTTP server toolkit. It handles parsing, connection management, HTTP/1.1 keep-alive, HTTP/2 over TLS, and request routing. That makes it tempting to write a three-line ListenAndServe call and call it production-ready. The default server, however, has no read or write timeouts, no body limit, no structured request logging, and no graceful shutdown.

This tutorial builds a small JSON service with the standard library and Go 1.22 or newer. It uses method-aware routing, middleware that records status and latency, bounded request bodies, explicit server timeouts, signal-driven graceful shutdown, and handler tests with httptest. The goal is not to recreate a framework; it is to make the default server safe for real traffic.

Create a testable mux

Go 1.22 extended http.ServeMux patterns to include an HTTP method and path parameters. A pattern such as "GET /items/{id}" routes only GET requests and exposes the id path value through r.PathValue("id"). This removes the need for a third-party router in many services.

Put route construction in a function that returns an http.Handler. A constructor makes tests independent and avoids package-level global state:

package main

import (
    "encoding/json"
    "errors"
    "net/http"
)

func newHandler() http.Handler {
    mux := http.NewServeMux()

    mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
        writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
    })

    mux.HandleFunc("GET /items/{id}", func(w http.ResponseWriter, r *http.Request) {
        id := r.PathValue("id")
        if id == "" {
            writeJSON(w, http.StatusBadRequest, map[string]string{"error": "missing id"})
            return
        }
        writeJSON(w, http.StatusOK, map[string]string{"id": id})
    })

    return mux
}

func writeJSON(w http.ResponseWriter, status int, value any) {
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(status)
    _ = json.NewEncoder(w).Encode(value)
}

Set headers before WriteHeader; once the status is written, later header changes are ignored. If encoding fails after the status is sent, the response is already committed. Log the error, but do not try to write a second error response. For handlers that must detect encoding failures before committing, encode into a buffer first and then write the bytes.

Add request logging and body limits

Middleware is a function from http.Handler to http.Handler. A logging middleware needs the response status, so wrap the writer:

type statusRecorder struct {
    http.ResponseWriter
    status int
    bytes  int
}

func (r *statusRecorder) WriteHeader(status int) {
    r.status = status
    r.ResponseWriter.WriteHeader(status)
}

func (r *statusRecorder) Write(p []byte) (int, error) {
    if r.status == 0 {
        r.status = http.StatusOK
    }
    n, err := r.ResponseWriter.Write(p)
    r.bytes += n
    return n, err
}

Then log method, path, status, bytes, and duration with log/slog:

func logging(logger *slog.Logger, next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        start := time.Now()
        rec := &statusRecorder{ResponseWriter: w}
        next.ServeHTTP(rec, r)

        status := rec.status
        if status == 0 {
            status = http.StatusOK
        }
        logger.Info("request",
            "method", r.Method,
            "path", r.URL.Path,
            "status", status,
            "bytes", rec.bytes,
            "duration", time.Since(start),
        )
    })
}

The wrapper embeds http.ResponseWriter, which is enough for ordinary JSON handlers. Streaming handlers that need http.Flusher or WebSocket upgrades that need http.Hijacker require a wrapper that forwards those interfaces; embedding alone hides them. If you use such handlers, use a library wrapper or implement the interfaces explicitly.

Limit the body before reading it:

func limitBody(max int64, next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        r.Body = http.MaxBytesReader(w, r.Body, max)
        next.ServeHTTP(w, r)
    })
}

MaxBytesReader returns an error when the limit is exceeded and closes the request body. Handlers must still check the error from json.Decoder.Decode; otherwise a truncated body may be treated as a valid request. A global limit is a good default. Per-route limits are better when one endpoint intentionally accepts large payloads.

Configure server timeouts

Create an http.Server with explicit timeouts. The zero-value defaults are too permissive for public traffic:

server := &http.Server{
    Addr:              ":8080",
    Handler:           logging(logger, limitBody(1<<20, newHandler())),
    ReadHeaderTimeout: 5 * time.Second,
    ReadTimeout:       10 * time.Second,
    WriteTimeout:      15 * time.Second,
    IdleTimeout:       60 * time.Second,
    MaxHeaderBytes:    1 << 20,
}

ReadHeaderTimeout bounds how long a client can take to send headers. ReadTimeout covers the entire request read, including the body. WriteTimeout covers the response write. IdleTimeout controls how long an idle keep-alive connection is retained. These values are policy decisions: an upload endpoint may need a longer read timeout, while an API that only accepts small JSON bodies can use aggressive values.

A handler-level context deadline is complementary, not a replacement. http.TimeoutHandler returns a 503 when a handler exceeds its budget, but the handler goroutine may continue unless it respects the request context. Prefer passing r.Context() into downstream calls and checking ctx.Err():

func withTimeout(d time.Duration, next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        ctx, cancel := context.WithTimeout(r.Context(), d)
        defer cancel()
        next.ServeHTTP(w, r.WithContext(ctx))
    })
}

Do not put secrets in log fields. Log a request id and the route, not authorization headers, cookies, or raw query strings that may contain tokens at the API boundary.

Shut down gracefully

Graceful shutdown has three steps: stop accepting new connections, let in-flight requests finish, and exit within a deadline. signal.NotifyContext ties the signal to a context:

func run() error {
    logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
    server := &http.Server{
        Addr:              ":8080",
        Handler:           logging(logger, limitBody(1<<20, newHandler())),
        ReadHeaderTimeout: 5 * time.Second,
        ReadTimeout:       10 * time.Second,
        WriteTimeout:      15 * time.Second,
        IdleTimeout:       60 * time.Second,
    }

    ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
    defer stop()

    errCh := make(chan error, 1)
    go func() {
        errCh <- server.ListenAndServe()
    }()

    select {
    case err := <-errCh:
        if !errors.Is(err, http.ErrServerClosed) {
            return err
        }
        return nil
    case <-ctx.Done():
        shutdownCtx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
        defer cancel()
        if err := server.Shutdown(shutdownCtx); err != nil {
            return fmt.Errorf("shutdown: %w", err)
        }
        if err := <-errCh; !errors.Is(err, http.ErrServerClosed) {
            return err
        }
        return nil
    }
}

ListenAndServe always returns a non-nil error; http.ErrServerClosed is the expected result of a clean shutdown. Shutdown stops accepting connections and waits for active requests, but it does not wait for hijacked connections such as WebSockets. Track those separately if the service supports them.

The shutdown timeout should be shorter than the orchestrator’s termination grace period. If the platform sends SIGKILL after 30 seconds, waiting 60 seconds in Shutdown means the process is killed before it can report a clean exit. Expose a readiness endpoint that starts returning failure as soon as shutdown begins, so load balancers stop sending new traffic.

Test handlers without a live server

httptest.NewRecorder and httptest.NewRequest exercise the full handler stack without binding a port:

func TestHealth(t *testing.T) {
    req := httptest.NewRequest(http.MethodGet, "/healthz", nil)
    rec := httptest.NewRecorder()

    newHandler().ServeHTTP(rec, req)

    if rec.Code != http.StatusOK {
        t.Fatalf("status = %d, want 200", rec.Code)
    }
    if got := rec.Header().Get("Content-Type"); got != "application/json" {
        t.Fatalf("content-type = %q", got)
    }
}

Add tests for a wrong method, a missing path value, a body over the limit, and a malformed JSON body. For middleware, assert that the status recorder captures an implicit 200 when a handler writes without calling WriteHeader. For end-to-end behavior, httptest.NewServer gives a real URL and exercises the client/transport layer, but recorder tests are faster and more deterministic.

Common pitfalls

  • No timeouts. The default server is vulnerable to slow clients and resource exhaustion.
  • Ignoring ListenAndServe errors. A port conflict or TLS failure exits silently.
  • Assuming Shutdown cancels handlers. It waits; handlers must respect context deadlines.
  • Writing a second response after an encode error. The status is already committed.
  • Using a status wrapper that hides Flusher or Hijacker. Streaming and WebSocket handlers break.
  • Reading unbounded bodies. MaxBytesReader is a one-line defense.
  • Exposing pprof on the public listener. Use a separate internal port and authentication.
  • Trusting X-Forwarded-For from any client. Only trust proxy headers from a known proxy.

Conclusion

The Go standard library is enough for a reliable JSON service when the server is configured deliberately. Use method-aware mux patterns, construct handlers in a function, add bounded bodies and explicit timeouts, log status and latency, and shut down on signals with a deadline. Test the handler stack with httptest and cover the failure paths. Those choices matter more than whether the code uses a framework.

Sources: net/http documentation, Go 1.22 routing enhancements, log/slog documentation.

FAQ

Do I need a framework to build an HTTP API in Go?
No. The standard library covers routing, middleware, JSON encoding, timeouts, and graceful shutdown. Frameworks add conveniences such as route groups and parameter binding, but they are not required for a small or medium service.
Why does my Go server need ReadHeaderTimeout?
Without it, a client can open a connection and send headers slowly, holding resources indefinitely. This is the Slowloris pattern. Set ReadHeaderTimeout, ReadTimeout, WriteTimeout, and IdleTimeout explicitly instead of relying on the default server.
How long should graceful shutdown wait?
Wait longer than the slowest expected request but shorter than the orchestrator's termination grace period. If Kubernetes sends SIGKILL after 30 seconds, a 20-second shutdown deadline leaves time to finish or cancel work and exit cleanly.

Related Examples

Interactive Tools for This Topic