Skip to content

Instantly share code, notes, and snippets.

@suhanlee
Last active September 21, 2017 18:16
Show Gist options
  • Select an option

  • Save suhanlee/704b2366f951ee09bc680a2e2a5e34c5 to your computer and use it in GitHub Desktop.

Select an option

Save suhanlee/704b2366f951ee09bc680a2e2a5e34c5 to your computer and use it in GitHub Desktop.
http_cookie.go
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