英文:
How to add parameters to ServeHTTP?
问题
我想要向Gorilla添加一个中间件,用于在调用中添加额外的参数:
// 添加一个名为"message"的参数的中间件
func authCheck(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
message := "hello"
log.Info().Msgf("添加消息 %v", message)
// 我的问题核心在这里:如何将"message"传递给下一个处理函数
next.ServeHTTP(w, r)
})
}
func main() {
// (...)
r.HandleFunc("/check", check).Methods(http.MethodGet)
// (...)
r.Use(authCheck)
// (...)
}
func check(w http.ResponseWriter, r *http.Request) {
// 我想在这里使用"message",并将其传递给函数
w.Write([]byte(message))
}
在Go语言中,是否可以采用这种方法呢?
英文:
I would like to add a middleware to Gorilla that "enriches" the call with extra parameters:
// a middleware that adds a parameter "message"
func authCheck(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
message := "hello"
log.Info().Msgf("adding message %v", message)
// the core of my question is here: how to pass "message" further
next.ServeHTTP(w, r)
})
}
I would like to add message
as a parameter that could be ultimately used in a route:
main() {
// (...)
r.HandleFunc("/check", check).Methods(http.MethodGet)
// (...)
r.Use(authCheck)
// (...)
}
func check(w http.ResponseWriter, r *http.Request) {
// I would like to use "message" here, having it passed somehow to the function
w.Write([]byte(message))
}
Is such an approach possible in Go?
答案1
得分: 1
感谢评论和指导,我成功传递了变量。供参考:
type httpContextStruct struct {
user string
wazaa string
}
var httpContext httpContextStruct
func authCheck(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
httpContext = httpContextStruct{}
r = r.WithContext(context.WithValue(
r.Context(),
httpContext,
httpContextStruct{
user: "thisisme",
wazaa: "aaa",
},
))
next.ServeHTTP(w, r)
})
}
func check(w http.ResponseWriter, r *http.Request) {
myc := r.Context().Value(httpContext).(httpContextStruct)
w.Write([]byte(fmt.Sprintf("user: %v", myc.user)))
}
// 输出
// user: thisisme
英文:
Thanks to the comments and pointers, I managed to pass the variable. For reference:
type httpContextStruct struct {
user string
wazaa string
}
var httpContext httpContextStruct
func authCheck(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
httpContext = httpContextStruct{}
r = r.WithContext(context.WithValue(
r.Context(),
httpContext,
httpContextStruct{
user: "thisisme",
wazaa: "aaa",
},
))
next.ServeHTTP(w, r)
})
}
func check(w http.ResponseWriter, r *http.Request) {
myc := r.Context().Value(httpContext).(httpContextStruct)
w.Write([]byte(fmt.Sprintf("user: %v", myc.user)))
}
// output
// user: thisisme
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论