Last active
September 21, 2017 18:16
-
-
Save suhanlee/704b2366f951ee09bc680a2e2a5e34c5 to your computer and use it in GitHub Desktop.
http_cookie.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "net/http" | |
| "encoding/base64" | |
| "fmt" | |
| "time" | |
| ) | |
| func setMessage(w http.ResponseWriter, r *http.Request) { | |
| msg := []byte("Hello World") | |
| c := http.Cookie{ | |
| Name: "flash", | |
| Value: base64.URLEncoding.EncodeToString(msg), | |
| } | |
| http.SetCookie(w, &c) | |
| } | |
| func showMessage(w http.ResponseWriter, r *http.Request) { | |
| c, err := r.Cookie("flash") | |
| if err != nil { | |
| if err == http.ErrNoCookie { | |
| fmt.Fprintln(w, "No Message found") | |
| } | |
| } else { | |
| rc := http.Cookie { | |
| Name: "flash", | |
| MaxAge: -1, | |
| Expires: time.Unix(1, 0), | |
| } | |
| http.SetCookie(w, &rc) | |
| val, _ := base64.URLEncoding.DecodeString(c.Value) | |
| fmt.Fprintln(w, string(val)) | |
| } | |
| } | |
| func main() { | |
| server := http.Server { | |
| Addr: "127.0.0.1:8080", | |
| } | |
| http.HandleFunc("/set_message", setMessage) | |
| http.HandleFunc("/show_message", showMessage) | |
| server.ListenAndServe() | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment