I am trying to set a new context with information about a user in a middleware ServeHTTP http.Handler function. I can pass the new context to a function in the same page and it prints the new context correctly, however when I pass it to the next middleware handler the new context value is empty. The next middleware in this case is a logging function that wraps the full request as follows:
`wrappedMux := NewLogger(NewEnsureAuth(NewResponseHeader(mux, “X-Launchpad-Request-Id”, uuidV2.String())))
Following is the relevant code:
// Within the same file.
type EnsureAuth struct {
handler http.Handler
}
func doSomething(ctx context.Context) {
fmt.Printf("doSomething: myKey's value is %s\n", ctx.Value("Launchpad"))
// Output is: "doSomething: myKey's value is {Bugs Bunny bugs@large.net}"
}
func (ea *EnsureAuth) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if authResult.Authenticated {
// Create a new request context containing the authenticated user
newCtx := context.WithValue(r.Context(), "Launchpad", authResult.User)
// Create a new request using that new context
rWithUser := r.WithContext(newCtx)
doSomething(rWithUser.Context())
r.URL.Path = "/index.html"
w.Header().Set("Content-Type", "text/html")
w.WriteHeader(http.StatusOK)
// Call the real handler, passing the new request
ea.handler.ServeHTTP(w, rWithUser)
}
}
// In a different file.
func (l *Logger) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(os.Stderr, "Your User: %v", r.Context().Value("Launchpad"))
// Output is: "Your User: <nil>"
}
Any help would be much appreciated. If I can provide any further details please let me know.
Daryl