I’m making an attempt to set a brand new context with details about a consumer in a middleware ServeHTTP http.Handler perform. I can move the brand new context to a perform in the identical web page and it prints the brand new context appropriately, nevertheless once I move it to the subsequent middleware handler the brand new context worth is empty. The subsequent middleware on this case is a logging perform that wraps the complete request as follows:
`wrappedMux := NewLogger(NewEnsureAuth(NewResponseHeader(mux, “X-Launchpad-Request-Id”, uuidV2.String())))
Following is the related code:
// Inside the identical file.
kind EnsureAuth struct {
handler http.Handler
}
func doSomething(ctx context.Context) {
fmt.Printf("doSomething: myKey's worth is %sn", ctx.Worth("Launchpad"))
// Output is: "doSomething: myKey's worth is {Bugs Bunny bugs@massive.internet}"
}
func (ea *EnsureAuth) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if authResult.Authenticated {
// Create a brand new request context containing the authenticated consumer
newCtx := context.WithValue(r.Context(), "Launchpad", authResult.Consumer)
// Create a brand new request utilizing that new context
rWithUser := r.WithContext(newCtx)
doSomething(rWithUser.Context())
r.URL.Path = "/index.html"
w.Header().Set("Content material-Kind", "textual content/html")
w.WriteHeader(http.StatusOK)
// Name the actual handler, passing the brand new request
ea.handler.ServeHTTP(w, rWithUser)
}
}
// In a unique file.
func (l *Logger) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(os.Stderr, "Your Consumer: %v", r.Context().Worth("Launchpad"))
// Output is: "Your Consumer: <nil>"
}
Any assist could be a lot appreciated. If I can present any additional particulars please let me know.
Daryl
Following up on the issue I’m having passing the consumer context, I believe the problem is likely to be that the primary middleware name to the log handler (to get the request begin time) doesn’t but have the consumer context.
The subsequent middleware authenticates the consumer and provides the consumer context and after that I can certainly see and print the consumer context however after the opposite middleware chain is accomplished and we return to the logger to do the precise logging the consumer context is once more lacking.
I can’t make sure however plainly the logging middleware continues to be utilizing the unique http request regardless that I can see the consumer context within the request of the earlier middleware’s ServeHTTP name.
If anyone might shed any gentle on this, I positive would admire it.
Daryl