Go Web Frameworks interview question · Most asked
How do you test HTTP handlers in Go?
Summary
Use net/http/httptest: build a request with httptest.NewRequest, a recorder with httptest.NewRecorder, call router.ServeHTTP(rec, req), and assert on status, headers and body, usually in table-driven tests with t.Run.
Longer Answer
Inject dependencies via interfaces so tests use fakes. Run with go test -race ./.... Keep a few integration tests against a real database (e.g. in a container). Fiber apps use app.Test(req) instead.
Key Points
- httptest recorder, no server needed.
- Table-driven subtests.
- Interfaces + fakes; -race in CI.
Deep dive: Go Web Frameworks: Testing Go APIs
More most-asked Go Web Frameworks questions
- How should a Go service use database/sql correctly?
- How do you implement graceful shutdown for a Go HTTP server?
- Compare Gin, Echo, Chi and Fiber.
- What is the http.Handler interface, and why is it central to Go web development?
- How do you pass request-scoped values (like the current user) through middleware in Go?
- Do you need a web framework in Go? What does Go 1.22's ServeMux provide?
- How do you design consistent error responses in a Go API?