Go Web Frameworks interview question · Most asked

How do you pass request-scoped values (like the current user) through middleware in Go?

Create a free account to save this page, take notes and track your progress. Sign in

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

← All Go Web Frameworks questions

Was this page helpful?