我在以 tmpl.Execute
开头的行上收到 undefined: msg
错误。你应该如何在 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})
}
最佳答案
您应该在 if
之外声明 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()})
}
关于cookies - 如何在 Go 中检索 cookie?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19988574/