Docs · Go / HTTP Services / Foundations

Go HTTP Service Foundations

Go HTTP Service Foundations

Go's standard library is enough to build a small HTTP service with a clear runtime boundary. The useful starting point is not a framework decision. It is an explicit module, a small handler surface, an owned http.Server, and tests that exercise the boundary through HTTP.

Start with a module

Create a module at the repository root and keep dependency ownership in go.mod:

go mod init example.com/orders
go mod tidy

go.mod records the module path and dependency requirements. go mod tidy keeps the module graph aligned with the packages actually imported by the source and tests.

A practical service layout is deliberately small:

cmd/orders/main.go       # process entrypoint and wiring
internal/orders/         # domain and application logic
internal/httpapi/        # handlers, decoding, and response mapping
internal/store/          # persistence boundary

The layout is a recommendation, not a rule enforced by Go. The important boundary is that main wires dependencies while handlers translate HTTP into application calls.

Use explicit HTTP boundaries

net/http models a handler as code that receives a response writer and a request. Keep the handler responsible for protocol concerns and move business rules into a service that can be tested without an HTTP server.

type OrderService interface {
    Create(ctx context.Context, input CreateOrderInput) (Order, error)
}

type Handler struct {
    orders OrderService
}

func (h Handler) CreateOrder(w http.ResponseWriter, r *http.Request) {
    order, err := h.orders.Create(r.Context(), CreateOrderInput{})
    if err != nil {
        http.Error(w, "could not create order", http.StatusInternalServerError)
        return
    }

    w.Header().Set("Content-Type", "application/json")
    _ = json.NewEncoder(w).Encode(order)
}

Pass r.Context() downward. It carries cancellation and deadlines from the request boundary, so database calls and downstream work can stop when the client or server no longer needs the result.

Own the server lifecycle

Use an explicit http.Server when the service has production requirements. It makes timeouts and shutdown behavior visible at the process boundary:

server := &http.Server{
    Addr:              ":8080",
    Handler:           mux,
    ReadHeaderTimeout: 5 * time.Second,
    WriteTimeout:      15 * time.Second,
    IdleTimeout:       60 * time.Second,
}

On termination, call server.Shutdown with a bounded context, then close dependencies such as the database pool.

shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

if err := server.Shutdown(shutdownCtx); err != nil {
    log.Printf("graceful shutdown failed: %v", err)
}

The exact timeout is an operational decision. It should be long enough for normal in-flight requests and short enough for the platform to replace the process predictably.

Test at the HTTP seam

Use httptest.NewRequest and httptest.NewRecorder for handler tests. Assert the status code, content type, response body, and the service call inputs. Add an integration test for the real router and dependency wiring when route registration or middleware order is important.

Production checklist

  • go.mod and go.sum are reviewed with the change.
  • The process listens on the platform-provided port when one is configured.
  • Request work receives and respects context.Context.
  • Server timeouts are explicit and justified.
  • SIGTERM triggers bounded graceful shutdown.
  • Health endpoints do not claim readiness before critical dependencies are ready.
  • Handler and router tests cover success, validation, not-found, and dependency failure paths.

References

Agent access

Choose a representation.

Published content only
Human pageYou are reading the human-facing canonical page.
Current page

Both machine-readable links refer to this same published item and preserve its identity, relationships, freshness, and body.