How to use golang 1.7 context with http.Request (for authentication)

I have a function IsAuthenticatedto authenticate a request (JWT verification in the header Authorization)

func IsAuthenticated(a *framework.AppContext, r *http.Request) (int, error) {
  // ... do authentication. user is authenticated User object
  ctx := context.WithValue(r.Context(), "user", user)
  r = r.WithContext(ctx) 
  return 200, nil
} 

I found that it r = r.WithContext(ctx)doesn't seem to override the request object? How do I implement this? Should I request a query instead?

+4
source share
1 answer

It’s not clear to me exactly how you show the “middleware” or how it is executed. Since you only change a local variable rand never give it to anyone else, you cannot change it outside of your function.

, , 1.7, :

func IsAuthenticated(next http.Handler) http.Handler{
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request){
       //authenticate. Set cookies.
       //403 if not authenticated, etc.
       ctx := context.WithValue(r.Context(), "user",u)
       next(w,r.WithContext(ctx))
    })
}

:

http.Handle("/foo/bar", IsAuthenticated(myHandler))

( - alice, .)

, myHandler, , IsAuthenticated, - :

user := r.Context().Get("user").(*User)

+5

Source: https://habr.com/ru/post/1658580/


All Articles