I am trying to append value of my ID
to context in my auth
middleware, which verifies user and pass it to my API handler.
I want to verify JWT in middleware and pass the id to handler for further use.
I am trying to access the context with value in handler but not able to access it but at a same when I access the same context with value (attached to request) in the middleware itself ,I am getting the value.
Attaching code and logs
route:
addProductDistHandler := middlewares.Auth(client, log)
r.Handle("/add-product-distributor", addProductDistHandler(http.HandlerFunc(handlers.AddProductDist(log, client))))
auth middleware code :
` logger.InfoLog.Printf("user.ObjectID %T",user.ObjectID)
logger.InfoLog.Printf("user.ObjectID %v",user.ObjectID)
// Add user ID to request context
ctx := context.WithValue(r.Context(), userIDKey, user.ObjectID) // Assuming user.ObjectID is a primitive.ObjectID
r = r.WithContext(ctx)
logger.InfoLog.Printf("context : %T => %v",ctx,ctx)
distID, _ := r.Context().Value(userIDKey).(string)
logger.InfoLog.Printf("distID : %s",distID)
// Call the next handler
next.ServeHTTP(w, r)`
handler’s code :
distID, ok := r.Context().Value(userIDKey).(string)
if !ok {
logger.InfoLog.Println("userIDKey is not of type string or is nil")
// Handle the case where userIDKey is not of type string or is nil
helpers.EncodeJSON(w, http.StatusInternalServerError, "userIDKey is not of type string or is nil", nil)
return
}
logs
NFO 2024/06/21 23:36:46 cookie retrieved successfully
INFO 2024/06/21 23:36:46 ObjectID("66757f98606b94271a05cd24")
INFO 2024/06/21 23:36:46 user.ObjectID string
INFO 2024/06/21 23:36:46 user.ObjectID 66757f98606b94271a05cd24
INFO 2024/06/21 23:36:46 context : *context.valueCtx => context.Background.WithValue(type *http.contextKey, val <not Stringer>).WithValue(type *http.contextKey, val [::1]:8000).WithCancel.WithCancel.WithValue(type mux.contextKey, val <not Stringer>).WithValue(type mux.contextKey, val <not Stringer>).WithValue(type middlewares.contextKey, val 66757f98606b94271a05cd24)
INFO 2024/06/21 23:36:46 distID : 66757f98606b94271a05cd24
INFO 2024/06/21 23:36:46 userIDKey is not of type string or is nil
Inshort I want to access value appended in middleware func to request with the help of context into my handler and I am unable to do so
I tried variety of things but failed
user25606885 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.