2013-11-14 106 views
0

我收到undefined: msg錯誤,開頭爲tmpl.Execute。你應該如何在Go中檢索cookie?如何在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

順便說一句,你可能會發現大猩猩/會話有用:http://www.gorillatoolkit.org/pkg/sessions - 簡單的API,你可以(非常容易)如果需要,可以更改Redis/DB /其他服務器端商店的CookieStore。 – elithrar

回答

1

你應該申報msgif外:

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()}) 
    } 
+1

沒有必要像'msg,err:= r.Cookie(「msg」)一樣容易地定義'var msg * http.Cookie'行。 –