gpt4 book ai didi

go - 如何在Golang中将值从处理程序传递到中间件?

转载 作者:行者123 更新时间:2023-12-01 22:20:07 26 4
gpt4 key购买 nike

我试图将一些值从处理程序传递到中间件,但是它不起作用
处理程序

func (s *Server) handler(w http.ResponseWriter, r *http.Request) {

//code
v := map[string]string{
"created_by": CreatedBy,
"name": Name,
}
context.WithValue(r.Context(), "result", v)
api.Send(w, http.StatusOK, value)
}


中间件
func activity(next http.Handler) http.Handler {

return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
next.ServeHTTP(w, r)
result := getParams(r.Context())
fmt.Println("result", result)

})
}


func getParams(ctx context.Context) map[string]string {
if ctx == nil {
return nil
}

result, ok := ctx.Value("result").(map[string]string)
if ok {
return result
}

return nil
}


从上下文接收值之后,它显示为空的map。是将处理程序中的某些值传递给中间件的任何其他方法。

最佳答案

在这种情况下,您必须使用新的上下文创建copyhttp.Request

v := map[string]string{
"created_by": CreatedBy,
"name": Name,
}
rcopy := r.WithContext(context.WithValue(r.Context(), "result", v))
然后,您必须通过所有处理程序( http.Request)“发送” firstHandler -> activity -> lastHandler
func main() {
//firstHandler ➡️ activity ➡️ lastHandler`
http.Handle("/", firstHandler(activity(lastHandler())))
http.ListenAndServe(":80", nil)
}


func firstHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
v := map[string]string{
"created_by": CreatedBy,
"name": Name,
}
rcopy := r.WithContext(context.WithValue(r.Context(), "result", v))
next.ServeHTTP(w, rcopy)
})
}

func activity(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
result := getParams(r.Context())
fmt.Println("activity result", result)
next.ServeHTTP(w, r)
})
}

func lastHandler() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
result := getParams(r.Context())
fmt.Println("last result", result)
})
}

关于go - 如何在Golang中将值从处理程序传递到中间件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64032756/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com