POSTMAN中未设置Cookie。

huangapple go评论80阅读模式
英文:

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"))
}

huangapple
  • 本文由 发表于 2022年1月15日 20:55:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/70721633.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定