Last active
September 20, 2024 18:21
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"fmt" | |
"log" | |
"net/http" | |
) | |
type MyContext struct { | |
ID int | |
Name string | |
} | |
// ContextKey is a custom type to prevent key collisions in the context | |
type ContextKey string | |
const userContextKey ContextKey = "user" | |
// Middleware to inject User data into request context | |
func userMiddleware(next http.Handler) http.Handler { | |
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
// Simulate fetching user data, e.g., from a session or token | |
user := &MyContext{ | |
ID: 42, | |
Name: "N S", | |
} | |
// Create a new context with user data | |
ctx := context.WithValue(r.Context(), userContextKey, user) | |
// Call the next handler with the updated context | |
next.ServeHTTP(w, r.WithContext(ctx)) | |
}) | |
} | |
// Handler to retrieve and use User data from the context | |
func helloHandler(w http.ResponseWriter, r *http.Request) { | |
user, ok := Context(r) | |
if !ok { | |
http.Error(w, "User not found", http.StatusInternalServerError) | |
} | |
fmt.Fprintf(w, "Hello, %s (ID: %d)", user.Name, user.ID) | |
} | |
func main() { | |
mux := http.NewServeMux() | |
// Register handler with the middleware | |
mux.Handle("/", userMiddleware(http.HandlerFunc(helloHandler))) | |
log.Println("Server is running on :8080") | |
http.ListenAndServe(":8080", mux) | |
} | |
func Context(r *http.Request) (*MyContext, bool) { | |
user, ok := r.Context().Value(userContextKey).(*MyContext) | |
return user, ok | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment