Using Http Context to Add User Info

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}"

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)

                r.URL.Path = "/index.html"
                w.Header().Set("Content-Type", "text/html")

                // 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.


Following up on the problem I am having passing the user context, I think the issue might be that the first middleware call to the log handler (to get the request start time) does not yet have the user context.

The next middleware authenticates the user and adds the user context and after that I can indeed see and print the user context but after the other middleware chain is completed and we return to the logger to do the actual logging the user context is again missing.

I can’t be sure but it seems that the logging middleware is still using the original http request even though I can see the user context in the request of the previous middleware’s ServeHTTP call.

If anybody could shed any light on this, I sure would appreciate it.


This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.