Home > Back-end >  Go: How to use context value in a variable?
Go: How to use context value in a variable?

Time:01-11

I am using context to attach user payload(userId specifically) in a middleware for my go rest application

// middleware
    // attaching payload to the request context
        claimsWithPayload, _ := token.Claims.(*handlers.Claims)
        ctx := context.WithValue(r.Context(), "userid", claimsWithPayload.Id)
        req := r.WithContext(ctx)
        h := http.HandlerFunc(handler)
        h.ServeHTTP(w, req)

And later in a http handler, I need to extract that userid as string/integer but context().Value() returns an interface{}

// handler 
a := r.Context().Value("userid") // THIS returns an interface{}
response := []byte("Your user ID is"   a) //            
  •  Tags:  
  • Related