Learn / Go Service Engineering
HTTP Service Basics
Build a small JSON API with standard handlers, structured errors, timeouts, and a simple project layout.
Course: Go Service Engineering. Level: Intermediate. Topic: Reliable services.
Stage: basic - Basic service contracts - Go HTTP service contracts. Start with handlers that expose context, JSON boundaries, timeouts, and structured errors clearly.
Outcomes
- Create context-aware handlers.
- Decode and encode JSON safely.
- Configure server timeouts.
Concepts
- http.Handler
- ServeMux
- JSON decoder
- server timeout
Concept flow
Show how go http service contracts moves from trigger to implementation outcome in Go Services.
- Client
- ServeMux
- Handler
- Service
- JSON response
Session flow
- Model http.Handler (concept, 8 min) — Name the decisions behind http.Handler before writing code.
- Create context-aware handlers.
- Explain where http.Handler belongs in ticket processing platform.
- Build the vertical slice (walkthrough, 15 min) — Implement the smallest useful slice in cmd/api/main.go.
- Decode and encode JSON safely.
- Connect ServeMux to a working example.
- Verify and harden (exercise, 10 min) — Add read and write timeouts.
- Configure server timeouts.
- Record one risk or follow-up before moving on.
Code example
Go in cmd/api/main.go.
package main
import (
"log/slog"
"net/http"
"time"
)
func main() {
mux := http.NewServeMux()
mux.HandleFunc("POST /tickets", createTicket)
server := &http.Server{
Addr: ":8080",
Handler: requestLogger(mux),
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
}
slog.Info("api listening", "addr", server.Addr)
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
slog.Error("api stopped", "error", err)
}
}
func createTicket(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusCreated)
}
func requestLogger(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
slog.InfoContext(r.Context(), "request", "method", r.Method, "path", r.URL.Path)
next.ServeHTTP(w, r)
})
}
Walkthrough examples
- HTTP Service Basics in a ticket processing platform — A team is extending a small Go service plus worker and needs this lesson's pattern to be clear enough for review, testing, and future maintenance.
- File: cmd/api/main.go
- File: tests/http-service-basics.spec
- File: docs/go-services/http-service-basics.md
- Start from the provided Go snippet and make the intent visible in names and boundaries.
- Apply the checklist item "Use request context" before adding extra behavior.
- Write down how the implementation changes when ServeMux fails or becomes slow.
Practice
- Create one POST handler.
- Return a structured error for invalid JSON.
- Add read and write timeouts.
Checklist
- Use request context
- Limit request body size
- Set server timeouts
- Return consistent JSON errors
Quiz prompts
- Why set HTTP server read and write timeouts? — Timeouts protect service resources when clients are slow or connections stall.
- A teammate wants to hide http.Handler inside a convenient helper. What should you check first? — Place http.Handler at the boundary that keeps ticket processing platform behavior explicit, testable, and reviewable.
- Which artifact best proves this Go Services lesson is ready for review? — Production-ready learning needs evidence: a test, trace, command, screenshot, or log that catches the risk again.
- Basic service contracts: a teammate says the happy path works, but "Handler contract" is still implicit. What should you ask for before merging? — Handler contract belongs in the basic stage only when the decision is visible, testable, and tied to a realistic failure mode.
- A reviewer has five minutes to evaluate this basic Go Services slice. Which evidence is strongest? — Build the basic Go service shell: one typed JSON endpoint, server timeouts, request limits, and a consistent error envelope.
Flashcards
- Basic service contracts: what decision does "Handler contract" force you to make? Make each handler own decoding, validation, service delegation, and response encoding explicitly. Evidence prompt: Write one POST handler with request size limits and a typed error response.
- Basic service contracts: what decision does "Timeout defaults" force you to make? Protect the process from slow clients before the service handles real traffic. Evidence prompt: Add server timeouts and note what each timeout prevents.
- Basic service contracts: what decision does "Error envelope" force you to make? Return consistent JSON errors so clients do not parse ad hoc strings. Evidence prompt: Replace one plain-text error with a structured JSON error contract.
- In Go Services, what should you remember about http.Handler? http.Handler matters here because it supports "Create context-aware handlers.".
- In Go Services, what should you remember about ServeMux? ServeMux matters here because it supports "Decode and encode JSON safely.".
- In Go Services, what should you remember about JSON decoder? JSON decoder matters here because it supports "Configure server timeouts.".
- In Go Services, what should you remember about server timeout? server timeout matters here because it supports "Create context-aware handlers.".
Labs
- Ship a http service basics slice — Extend a small Go service plus worker with a small but reviewable feature that proves the lesson's architecture in code.
- Build the basic Go service shell: one typed JSON endpoint, server timeouts, request limits, and a consistent error envelope.
- Write one POST handler with request size limits and a typed error response.
- Add server timeouts and note what each timeout prevents.
- Replace one plain-text error with a structured JSON error contract.
- Create one POST handler.
- Return a structured error for invalid JSON.
- The lab demonstrates the basic service contracts outcome without skipping earlier contract evidence.
- Each subtopic has a concrete artifact: Handler contract, Timeout defaults, Error envelope.
- The review notes explain how this level changes ownership, verification, or operational risk.
Challenge
- Review-ready http service basics (Core) — Build the basic Go service shell: one typed JSON endpoint, server timeouts, request limits, and a consistent error envelope.
- All checklist items are either implemented or documented with a reason.
- The change can be understood from cmd/api/main.go plus one short note.
- The concept diagram names ownership, failure handling, and verification points.
- A teammate could run the verification steps without asking for hidden context.
Canonical lesson URL