Home > other >  Cookie is not set at the POSTMAN
Cookie is not set at the POSTMAN

Time:01-16

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?.

CodePudding user response:

set cookie first, then write a response. Example:

http.SetCookie(w, cookie)
w.Write([]byte("Cookie set Successfully"))

CodePudding user response:

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"))
}
  •  Tags:  
  • Related