We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

User Context

Most backend services require authentication on most HTTP handlers.

In Linko, only authenticated users can create short URLs via Basic Auth, using the fixed user list in auth.go.

When a request is authenticated, we already store the username in request context for handlers. Now we also want requestLogger to include it in the final "Served request" log.

Pointer-Based Log Context

The clean way to do this is to put a pointer to a shared struct in context before serving the request. Downstream middleware and handlers can mutate it, and requestLogger can read final values after next.ServeHTTP(...) returns.

const logContextKey contextKey = "log_context"

type LogContext struct {
	Username string
}

Why this helps:

  • One shared object for request-scoped logging fields.
  • It scales beyond just username (we'll add more fields in the next lesson).
  • It avoids global state while still letting downstream code communicate back to the logger.

Assignment

Include the authenticated username in request logs.

Rebuild your app with -ldflags, then run it with ENV and LINKO_LOG_FILE set:

go build \
  -ldflags "-X boot.dev/linko/internal/build.GitSHA=$(git rev-parse HEAD) -X boot.dev/linko/internal/build.BuildTime=$(date -u '+%Y-%m-%dT%H:%M:%SZ')" \
  -o linko &&
LINKO_LOG_FILE=linko.access.log ENV=development ./linko

Run and submit the CLI tests from the root of the Linko repo.