context:上下文,不仅可以设置超时控制Goroutine,还可在上下文中进行传值
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", mid(home))
mux.HandleFunc("/login", login)
log.Fatal(mux.ListenAndServe(":8099", mux))
}
func home(w http.ResponseWriter, r *http.Request) {
name := r.Context().Value("name")
fmt.Fprintf(w, "%s\n", name)
}
func login(w http.ResponseWriter, r *http.Request) {
if r.URL.Query().Get("user") != "root" {
http.Error(w, http.StatusText(401), 401)
return
}
cookie := &http.Cookie{Name: "Test"}
http.SetCookie(w, cookie)
http.Redirect(w, r, "/", 302)
}
func mid(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie("Name")
if err != nil || cookie == nil {
http.Error(w, http.StatusText(401), 401)
return
}
next(w, r.WithContext(context.WithValue(r.Context(), "Name", cookie)))
}
}
网友评论