英文:
Cookie is not set at the POSTMAN
问题
我正在尝试使用Golang编写以下代码,在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中检查了"send"按钮下面的"cookie"按钮,发现cookie并不存在。请问有人可以解释我做错了什么吗?
英文:
Am trying to set a cookie at the POSTMAN by writing the code blow using Golang
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)
}
So after i ran this program and i checked the POSTMAN "cookie" botton below the "send"
botton and i realised that the cookie is not there.
Pls can anybody explain where am doing things wrong?.
答案1
得分: 1
首先设置cookie,然后编写响应。示例代码如下:
http.SetCookie(w, cookie)
w.Write([]byte("Cookie设置成功"))
英文:
set cookie first, then write a response. Example:
http.SetCookie(w, cookie)
w.Write([]byte("Cookie set Successfully"))
答案2
得分: 0
我后来意识到,如果先向响应体写入内容,就无法设置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设置成功"))
}
英文:
I later realized that you can not set cookie if write to the response
body first, cookie must be set first then other messages to the
response bodycan be follow:
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"))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论