Reputation: 861
I have the following code and works fine:
func main() {
http.HandleFunc("/", samplePage)
_ = http.ListenAndServe(":8080", nil)
}
func samplePage(w http.ResponseWriter, r *http.Request) {
expiration := time.Now().Add(time.Hour)
cookie := http.Cookie{Name: "username", Value: "XXX", Expires: expiration}
http.SetCookie(w, &cookie)
fmt.Fprintln(w, cookie.Value)
fmt.Fprintln(w, cookie.Expires)
}
It gives me
XXX
2016-03-29 17:57:02.7077906 -0700 PDT
However, if I print the following, it doesn't work:
cookie2, err := r.Cookie("username")
checkErr(err) //no error is found
fmt.Fprintln(w, cookie2.Value)
fmt.Fprintln(w, cookie2.Expires)
This gives me
XXX
0001-01-01 00:00:00 +0000 UTC
Looks like the "Value" works but "Expires" doesn't. I would like to use Cookie for user login. Could anyone tell me how to make "cookie2" work?
p.s. I also found the following question: Can't get cookie expiration time in golang It is very similar to my problem but the answer says we cannot use cookie in this way. If this is true then may I know how everyone is using cookie?
Thank you
Upvotes: 2
Views: 1609
Reputation: 555
You should request the cookie with name "Expiry" and you'll get the expiry you have set
Upvotes: -1