Golang net/http.SetCookie() function example

package net/http

Golang net/http.SetCookie() function usage example

 func home(w http.ResponseWriter, r *http.Request) {

 // setup cookie for deployment
 // see http://golang.org/pkg/net/http/#Request.Cookie

 // we will try to drop the cookie, if there's error
 // this means that the same cookie has been dropped
 // previously and display different message
 c, err := r.Cookie("timevisited") //

 expire := time.Now().AddDate(0, 0, 1)

 cookieMonster := &http.Cookie{
 Name:  "timevisited",
 Expires: expire,
 Value: strconv.FormatInt(time.Now().Unix(), 10),
 }

 // http://golang.org/pkg/net/http/#SetCookie
 // add Set-Cookie header
 http.SetCookie(w, cookieMonster)

 if err != nil {
 w.Write([]byte("Welcome! first time visitor!"))
 } else {
 lasttime, _ := strconv.ParseInt(c.Value, 10, 0)
 html := "Hey! Hello again!, your last visit was at "
 html = html + time.Unix(lasttime, 0).Format("15:04:05")
 w.Write([]byte(html))
 }
  }

See full example at : https://www.socketloop.com/tutorials/golang-drop-cookie-to-visitor-s-browser-and-http-setcookie-example

Reference :

http://golang.org/pkg/net/http/#SetCookie

Advertisement