Skip to content

Instantly share code, notes, and snippets.

@chy168
Last active August 29, 2015 14:16
Show Gist options
  • Save chy168/8275b2802efea1e98379 to your computer and use it in GitHub Desktop.
Save chy168/8275b2802efea1e98379 to your computer and use it in GitHub Desktop.
Go HTTP Server Cookie Example
package main
import (
"io"
"log"
)
import "net/http"
func indexHandler(w http.ResponseWriter, req *http.Request) {
//expire := time.Now().AddDate(0, 0, 1)
//cookie := http.Cookie{"test", "tcookie", "/", "www.sliceone.com", expire, expire.Format(time.UnixDate), 86400, true, true, "test=tcookie", []string{"test=tcookie"}}
//req.AddCookie(&cookie)
http.SetCookie(w, &http.Cookie{Name: "cookie-1", Value: "one", MaxAge: 3600})
http.SetCookie(w, &http.Cookie{Name: "cookie-2", Value: "two", MaxAge: 3600})
io.WriteString(w, `{"status":"ok", "message":"create cookie"}`)
}
func deleteHandler(w http.ResponseWriter, req *http.Request) {
//expire := time.Now().AddDate(0, 0, 1)
//cookie := http.Cookie{"test", "tcookie", "/", "www.sliceone.com", expire, expire.Format(time.UnixDate), 86400, true, true, "test=tcookie", []string{"test=tcookie"}}
//req.AddCookie(&cookie)
//http.SetCookie(w, &http.Cookie{Name: "cookie-1", MaxAge: -1})
http.SetCookie(w, &http.Cookie{Name: "cookie-2", MaxAge: -1})
io.WriteString(w, `{"status":"ok", "message":"cookie deleted"}`)
}
func Log(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("%s %s %s", r.RemoteAddr, r.Method, r.URL)
handler.ServeHTTP(w, r)
})
}
func main() {
http.HandleFunc("/cookie/new", indexHandler)
http.HandleFunc("/cookie/del", deleteHandler)
http.ListenAndServe(":9999", Log(http.DefaultServeMux))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment