美文网首页golang 编程笔记
【golang】HTTP服务器的request互相传递数据

【golang】HTTP服务器的request互相传递数据

作者: dongzd | 来源:发表于2020-03-14 15:40 被阅读0次

    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)))
        }
    
    }
    

    相关文章

      网友评论

        本文标题:【golang】HTTP服务器的request互相传递数据

        本文链接:https://www.haomeiwen.com/subject/pyhwshtx.html