如何在Go中检索Cookie

如何在Go中检索Cookie

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

最佳答案

您应该在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()})
    }

关于cookies - 如何在Go中检索Cookie?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19988574/

10-09 04:01