Cookies 如何在Go中检索cookie?

Cookies 如何在Go中检索cookie?,cookies,go,Cookies,Go,我在以tmpl.Execute开头的行中得到undefined:msg错误。你应该如何在围棋中找回饼干 func contact(w http.ResponseWriter, r *http.Request) { if r.Method == "POST" { r.ParseForm() for k, v := range r.Form { fmt.Println("k:", k, "v:", v) }

我在以
tmpl.Execute
开头的行中得到
undefined:msg
错误。你应该如何在围棋中找回饼干

func contact(w http.ResponseWriter, r *http.Request) {
    if r.Method == "POST" {
        r.ParseForm()
        for k, v := range r.Form {
            fmt.Println("k:", k, "v:", v)
        }
        http.SetCookie(w, &http.Cookie{Name: "msg", Value: "Thanks"})
        http.Redirect(w, r, "/contact/", http.StatusFound)
    }
    if msg, err := r.Cookie("msg"); err != nil {
        msg := ""
    }
    tmpl, _ := template.ParseFiles("templates/contact.tmpl")
    tmpl.Execute(w, map[string]string{"Msg": msg})
}

如果,则应在
之外声明
msg

    func contact(w http.ResponseWriter, r *http.Request) {
        var msg *http.Cookie

        if r.Method == "POST" {
            r.ParseForm()
            for k, v := range r.Form {
                fmt.Println("k:", k, "v:", v)
            }
            http.SetCookie(w, &http.Cookie{Name: "msg", Value: "Thanks"})
            http.Redirect(w, r, "/contact/", http.StatusFound)
        }

        msg, err := r.Cookie("msg")
        if err != nil {
            // we can't assign string to *http.Cookie
            // msg = ""

            // so you can do
            // msg = &http.Cookie{}
        }

        tmpl, _ := template.ParseFiles("templates/contact.tmpl")
        tmpl.Execute(w, map[string]string{"Msg": msg.String()})
    }

没有必要使用
var msg*http.Cookie
行,因为它可以在
msg,err:=r.Cookie(“msg”)
中定义。顺便说一句,您可能会发现gorilla/sessions很有用:-简单的API,如果需要,您可以(非常容易)将CookieStore更改为Redis/DB/其他服务器端存储。