如何在Go中检索cookie?

时间:2013-11-14 21:17:54

标签: cookies go

我在以undefined: msg开头的行上收到tmpl.Execute错误。你如何在Go中检索cookie?

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

1 个答案:

答案 0 :(得分:2)

您应在msg

之外声明if
    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()})
    }