---
id: 45
type: docs
title: "Go HTTP Service Foundations"
slug: "go-http-service-foundations"
canonical_url: "https://docs.phatysd.me/content/go-http-service-foundations"
status: published
revision: 1
published_at: "2026-09-19T17:51:06.174Z"
updated_at: "2026-09-19T17:51:06.174Z"
hierarchy_path: "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
    canonical_url: "https://docs.phatysd.me/content/why-go-keeps-http-services-small"
  - slug: "fiber-production-api-runbook"
    title: "Fiber Production API Runbook"
    type: docs
    canonical_url: "https://docs.phatysd.me/content/fiber-production-api-runbook"
---

# 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`:

```bash
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:

```text
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.

```go
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:

```go
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.

```go
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

- [Go modules tutorial](https://go.dev/doc/tutorial/call-module-code)
- [Writing web applications with `net/http`](https://go.dev/doc/articles/wiki)
- [`net/http` package reference](https://pkg.go.dev/net/http)
- [`context` package reference](https://pkg.go.dev/context)