[英]How to use golang 1.7 context with http.Request (for Authentication)
I have an IsAuthenticated
function to check if the request is authenticated (checking the JWT in the Authorization
header) 我有一个IsAuthenticated
函数来检查请求是否经过身份验证(检查Authorization
标头中的JWT)
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 find that it appears that r = r.WithContext(ctx)
does not override the request object? 我发现似乎r = r.WithContext(ctx)
没有覆盖请求对象? How should I implement this? 我该如何实现呢? Do I need to requrn a request instead? 我需要重新订购请求吗?
It is not clear to me exactly how what you show is a "middleware", or how it is being executed. 我不清楚你所展示的是什么是“中间件”,或者它是如何被执行的。 Since you are only changing your local variable r
, and never giving that to anyone else, there is no way your change wil be visible outside your function. 由于您只是更改本地变量r
,并且从不将其提供给其他任何人,因此您的更改无法在您的函数外部显示。
There have been a variety of middleware flavors in the go landscape, but since go 1.7 I have seen a lot more moving towards middleware functions of the form: 在go版本中有各种各样的中间件风格,但从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))
})
}
This can be used to chain handlers together like so: 这可以用于将处理程序链接在一起,如下所示:
http.Handle("/foo/bar", IsAuthenticated(myHandler))
(or use something like alice to make chaining middlewares even easier.) (或使用像alice这样的东西来使链接中间件更容易。)
This way, when myHandler
gets invoked, it will have the new request created by IsAuthenticated
, and it can fetch the user with something like: 这样,当myHandler
被调用时,它将具有由IsAuthenticated
创建的新请求,并且它可以通过IsAuthenticated
方式获取用户:
user := r.Context().Get("user").(*User)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.