作为一名 Go 程序员,我相对较新,我正在尝试为我的服务器构建一个自定义中间件。问题是它的行为不像我预期的那样。有人可以解释为什么我的上下文没有设置为ME吗?
package main
import (
"context"
"log"
"net/http"
"github.com/julienschmidt/httprouter"
)
func main() {
router := httprouter.New()
router.GET("/test", middlewareChain(contentType, name))
log.Print("App running on 8080")
log.Fatal(http.ListenAndServe(":8080", router))
}
func middlewareChain(h ...httprouter.Handle) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
r = r.WithContext(context.WithValue(r.Context(), "test", "You"))
log.Print("Set context to YOU")
for _, handler := range h {
handler(w, r, p)
}
}
}
func contentType(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
r = r.WithContext(context.WithValue(r.Context(), "test", "Me"))
log.Print("Set context to ME")
header := w.Header()
header.Set("Content-type", "application/json")
}
func name(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
log.Printf("Context: %s", r.Context().Value("test"))
}
互换的青春
相关分类