By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
The second deliverable exposes Relay over HTTP. The analyzer code does not change; you add a transport layer that decodes JSON, validates it, enforces a body limit, attaches a request ID and returns JSON errors with correct status codes. The rule that keeps this honest: handlers parse and delegate, they do not implement aggregation themselves.
Every response — success or failure — is JSON with a Content-Type. Errors share a shape so clients can parse them once. Request IDs are generated in middleware and echoed in a header; the logger and any future trace use the same ID to connect the lines. That single decision is what makes the observability lesson in step 26 possible.
internal/httpapi with a New(analyzer, store, logger) http.Handler constructor that returns a fully wired ServeMux.POST /v1/events, GET /v1/stats, GET /healthz and GET /readyz with JSON bodies and explicit status codes.X-Request-ID), structured logging, panic recovery and a 1 MiB body limit.service and level are required, status must be 100-599, unknown JSON fields are rejected.httptest.NewServer and run them with -race; test the 405 and oversized-body paths too.package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
)
type event struct {
Service string `json:"service"`
Level string `json:"level"`
Status int `json:"status"`
}
type stats struct {
Total int `json:"total"`
ByService map[string]int `json:"by_service"`
}
type relay struct {
mu sync.Mutex
events []event
}
func (r *relay) handleEvents(w http.ResponseWriter, req *http.Request) {
decoder := json.NewDecoder(io.LimitReader(req.Body, 1<<20))
decoder.DisallowUnknownFields()
var e event
if err := decoder.Decode(&e); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON body")
return
}
if e.Service == "" {
writeError(w, http.StatusBadRequest, "service is required")
return
}
r.mu.Lock()
r.events = append(r.events, e)
r.mu.Unlock()
writeJSON(w, http.StatusAccepted, map[string]string{"status": "accepted"})
}
func (r *relay) handleStats(w http.ResponseWriter, _ *http.Request) {
r.mu.Lock()
defer r.mu.Unlock()
out := stats{Total: len(r.events), ByService: map[string]int{}}
for _, e := range r.events {
out.ByService[e.Service]++
}
writeJSON(w, http.StatusOK, out)
}
func writeJSON(w http.ResponseWriter, status int, payload any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(payload)
}
func writeError(w http.ResponseWriter, status int, message string) {
writeJSON(w, status, map[string]string{"error": message})
}
var requestCounter int
func withRequestID(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requestCounter++
w.Header().Set("X-Request-ID", fmt.Sprintf("req-%d", requestCounter))
next.ServeHTTP(w, r)
})
}
func main() {
r := &relay{}
mux := http.NewServeMux()
mux.HandleFunc("POST /v1/events", r.handleEvents)
mux.HandleFunc("GET /v1/stats", r.handleStats)
server := httptest.NewServer(withRequestID(mux))
defer server.Close()
post := func(body string) {
resp, err := http.Post(server.URL+"/v1/events", "application/json", strings.NewReader(body))
if err != nil {
panic(err)
}
defer resp.Body.Close()
payload, _ := io.ReadAll(resp.Body)
fmt.Println(resp.StatusCode, resp.Header.Get("X-Request-ID"), strings.TrimSpace(string(payload)))
}
post(`{"service":"api","level":"info","status":200}`)
post(`{"level":"info","status":200}`)
resp, err := http.Get(server.URL + "/v1/stats")
if err != nil {
panic(err)
}
defer resp.Body.Close()
payload, _ := io.ReadAll(resp.Body)
fmt.Println(resp.StatusCode, strings.TrimSpace(string(payload)))
}# Run the API locally (uses http.Server with timeouts and shutdown in step 24).
go run ./cmd/relayd --addr 127.0.0.1:8080
# In another shell: ingest one event and read the aggregate.
curl -sS -X POST http://127.0.0.1:8080/v1/events \
-H 'Content-Type: application/json' \
-d '{"service":"api","level":"info","status":200}'
curl -sS http://127.0.0.1:8080/v1/stats
# The gate for this project part.
go vet ./...
go test ./internal/httpapi -race -v| Deliverable | Acceptance check |
|---|---|
| Routes | All four endpoints respond; wrong methods return 405 |
| Request ID | Every response carries X-Request-ID, including 400 and 500 responses |
| Validation | Missing fields, bad status and unknown fields return 400 with a JSON error body |
| Limits | A body over 1 MiB is rejected without buffering it in full |
| Panic safety | A deliberately panicking test handler returns 500 and the server keeps serving |
| Tests | go test ./internal/httpapi -race passes; httptest covers success and failure paths |
Key takeaways
Handlers decode, validate and delegate; aggregation stays in the domain package.
Middleware is composed around handlers and is the place for request IDs, logging and recovery.
Return JSON errors with stable status codes: 400 validation, 404 missing, 500 internal.
Bound request bodies and reject unknown fields to keep the API contract strict.
httptest.NewServer plus -race lets you test the full HTTP path without ports or flakiness.
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.
Don't lose this lesson
Create a free account to save your progress, keep your streak, and work toward a shareable certificate.