Go Web Frameworks interview question · Most asked
How do you pass request-scoped values (like the current user) through middleware in Go?
Summary
Store them in the request's context with context.WithValue, using an unexported key type to avoid collisions, pass r.WithContext(ctx) to the next handler, and read them with a typed helper.
Longer Answer
Frameworks offer equivalents (c.Set/c.Get in Gin, c.Set in Echo, c.Locals in Fiber), but context.Context is what you should pass into services and repositories so cancellation and deadlines flow through too. Don't use context values for optional function parameters.
Code Example
type ctxKey int
const userKey ctxKey = 0
func UserFrom(ctx context.Context) (string, bool) {
u, ok := ctx.Value(userKey).(string)
return u, ok
}
Key Points
- context.WithValue + private key type.
- Typed accessor helper.
- Pass ctx into services for cancellation.
Deep dive: Go Web Frameworks: Middleware
More most-asked Go Web Frameworks questions
- How do you test HTTP handlers in Go?
- 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?
- 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?