Am试图通过使用Golang 编写代码blow在POSTMAN设置cookie
sub := handlers.NewSunscribers(s)
router := mux.NewRouter()
router.HandleFunc("/sub/set", sub.SetCookie).Methods("POST")
log.Fatal(http.ListenAndServe(":8000", router))
type SubHandlers struct {
sub storage.Sub
}
func (s SubHandlers) SetCookie(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode("Am trying to set a cookie")
cookie := &http.Cookie{
Name: "name",
Value: "Biola",
MaxAge: 3000,
}
w.Write([]byte("Cookie set Successfully"))
http.SetCookie(w, cookie)
}
所以在我运行了这个程序之后,我检查了POSTMAN";cookie";botton低于";发送";botton和我意识到饼干不在那里。有人能解释一下我哪里做错了吗?。
首先设置cookie,然后编写响应。示例:
http.SetCookie(w, cookie)
w.Write([]byte("Cookie set Successfully"))
我后来意识到,如果写入响应,就不能设置cookie正文优先,必须先设置cookie,然后将其他消息发送到响应体可以如下:
func setCookie(w http.ResponseWriter, r *http.Request) {
cookie := &http.Cookie{
Name: "name",
Value: "Bola",
MaxAge: 300,
}
http.SetCookie(w, cookie)
w.Write([]byte("Cookie set Successfully"))
}