{"id":45,"type":"docs","title":"Go HTTP Service Foundations","slug":"go-http-service-foundations","canonicalUrl":"https://docs.phatysd.me/content/go-http-service-foundations","status":"published","revision":1,"publishedAt":"2026-09-19T17:51:06.174Z","updatedAt":"2026-09-19T17:51:06.174Z","hierarchyPath":"Go > HTTP Services > Foundations","topics":["Go","HTTP","Backend architecture"],"tags":["golang","go-http","modules","context","testing"],"related":[{"slug":"why-go-keeps-http-services-small","title":"Why Go Keeps HTTP Services Small","type":"blog","canonicalUrl":"https://docs.phatysd.me/content/why-go-keeps-http-services-small"},{"slug":"fiber-production-api-runbook","title":"Fiber Production API Runbook","type":"docs","canonicalUrl":"https://docs.phatysd.me/content/fiber-production-api-runbook"}],"body":"# Go HTTP Service Foundations\n\nGo's standard library is enough to build a small HTTP service with a clear\nruntime boundary. The useful starting point is not a framework decision. It is\nan explicit module, a small handler surface, an owned `http.Server`, and tests\nthat exercise the boundary through HTTP.\n\n## Start with a module\n\nCreate a module at the repository root and keep dependency ownership in\n`go.mod`:\n\n```bash\ngo mod init example.com/orders\ngo mod tidy\n```\n\n`go.mod` records the module path and dependency requirements. `go mod tidy`\nkeeps the module graph aligned with the packages actually imported by the\nsource and tests.\n\nA practical service layout is deliberately small:\n\n```text\ncmd/orders/main.go       # process entrypoint and wiring\ninternal/orders/         # domain and application logic\ninternal/httpapi/        # handlers, decoding, and response mapping\ninternal/store/          # persistence boundary\n```\n\nThe layout is a recommendation, not a rule enforced by Go. The important\nboundary is that `main` wires dependencies while handlers translate HTTP into\napplication calls.\n\n## Use explicit HTTP boundaries\n\n`net/http` models a handler as code that receives a response writer and a\nrequest. Keep the handler responsible for protocol concerns and move business\nrules into a service that can be tested without an HTTP server.\n\n```go\ntype OrderService interface {\n    Create(ctx context.Context, input CreateOrderInput) (Order, error)\n}\n\ntype Handler struct {\n    orders OrderService\n}\n\nfunc (h Handler) CreateOrder(w http.ResponseWriter, r *http.Request) {\n    order, err := h.orders.Create(r.Context(), CreateOrderInput{})\n    if err != nil {\n        http.Error(w, \"could not create order\", http.StatusInternalServerError)\n        return\n    }\n\n    w.Header().Set(\"Content-Type\", \"application/json\")\n    _ = json.NewEncoder(w).Encode(order)\n}\n```\n\nPass `r.Context()` downward. It carries cancellation and deadlines from the\nrequest boundary, so database calls and downstream work can stop when the\nclient or server no longer needs the result.\n\n## Own the server lifecycle\n\nUse an explicit `http.Server` when the service has production requirements. It\nmakes timeouts and shutdown behavior visible at the process boundary:\n\n```go\nserver := &http.Server{\n    Addr:              \":8080\",\n    Handler:           mux,\n    ReadHeaderTimeout: 5 * time.Second,\n    WriteTimeout:      15 * time.Second,\n    IdleTimeout:       60 * time.Second,\n}\n```\n\nOn termination, call `server.Shutdown` with a bounded context, then close\ndependencies such as the database pool.\n\n```go\nshutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\ndefer cancel()\n\nif err := server.Shutdown(shutdownCtx); err != nil {\n    log.Printf(\"graceful shutdown failed: %v\", err)\n}\n```\n\nThe exact timeout is an operational decision. It should be long enough for\nnormal in-flight requests and short enough for the platform to replace the\nprocess predictably.\n\n## Test at the HTTP seam\n\nUse `httptest.NewRequest` and `httptest.NewRecorder` for handler tests. Assert\nthe status code, content type, response body, and the service call inputs. Add\nan integration test for the real router and dependency wiring when route\nregistration or middleware order is important.\n\n## Production checklist\n\n- `go.mod` and `go.sum` are reviewed with the change.\n- The process listens on the platform-provided port when one is configured.\n- Request work receives and respects `context.Context`.\n- Server timeouts are explicit and justified.\n- SIGTERM triggers bounded graceful shutdown.\n- Health endpoints do not claim readiness before critical dependencies are ready.\n- Handler and router tests cover success, validation, not-found, and dependency failure paths.\n\n## References\n\n- [Go modules tutorial](https://go.dev/doc/tutorial/call-module-code)\n- [Writing web applications with `net/http`](https://go.dev/doc/articles/wiki)\n- [`net/http` package reference](https://pkg.go.dev/net/http)\n- [`context` package reference](https://pkg.go.dev/context)"}