我在以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})
}
答案 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()})
}