How do I pass request-scoped values via context without abuse?

In Go, it's essential to manage request-scoped values effectively while avoiding misuse of the context package that can lead to issues in your application. Below is an example demonstrating how to properly pass request-scoped values using the context without overusing it.

Keywords: Go, context, request-scoped values, middleware
Description: Learn how to pass request-scoped values via context in Go without abusing it, using best practices and examples for effective handling.

// Example of passing request-scoped values in Go context

package main

import (
    "context"
    "fmt"
    "net/http"
)

// Define a key type for context
type contextKey string

const userKey contextKey = "user"

// Middleware to set the user in the context
func userMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        user := "John Doe" // Example user
        ctx := context.WithValue(r.Context(), userKey, user)
        next.ServeHTTP(w, r.WithContext(ctx))
    })
}

// Handler function to demonstrate accessing context value
func handler(w http.ResponseWriter, r *http.Request) {
    user := r.Context().Value(userKey)
    fmt.Fprintf(w, "Hello, %s!", user)
}

func main() {
    http.Handle("/", userMiddleware(http.HandlerFunc(handler)))
    http.ListenAndServe(":8080", nil)
}
    

Keywords: Go context request-scoped values middleware