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 :
Advertisement
Something interesting
Tutorials
+16.3k Golang : How to extract links from web page ?
+36.4k Golang : Convert date or time stamp from string to time.Time type
+6k PHP : How to check if an array is empty ?
+6.1k Golang : Grab news article text and use NLP to get each paragraph's sentences
+8.3k Golang : Implementing class(object-oriented programming style)
+87.7k Golang : How to convert character to ASCII and back
+23.9k Golang : Call function from another package
+9.4k Golang : Detect Pascal, Kebab, Screaming Snake and Camel cases
+22.1k Golang : Repeat a character by multiple of x factor
+21.3k Golang : Create and resolve(read) symbolic links
+17k Golang : Covert map/slice/array to JSON or XML format