英文:
How to retrieve a cookie in Go?
问题
我在以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})
}
英文:
I'm getting undefined: msg
error on the line begining with tmpl.Execute
. How are you supposed to retrieve cookies in Go?
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
得分: 2
你应该在 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 {
// 我们不能将字符串赋值给 *http.Cookie
// msg = ""
// 所以你可以这样做
// msg = &http.Cookie{}
}
tmpl, _ := template.ParseFiles("templates/contact.tmpl")
tmpl.Execute(w, map[string]string{"Msg": msg.String()})
}
英文:
You should declare msg
outside the 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()})
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论