2017年6月16日 星期五

Golang : Cookie




package main

import (
 "fmt"
 "log"
 "net/http"
 "time"
)

func index(w http.ResponseWriter, r *http.Request) {
 fmt.Fprintf(w, "Hello world")
        
        cookie, _ := r.Cookie("username")
 fmt.Println(cookie.Value, " is visit this site")
}

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

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

 cookie := http.Cookie{Name: "username", Value: "test", Expires: expires}
 http.SetCookie(w, &cookie)

 fmt.Fprintf(w, "I will help you to setup cookie.") //must write after setup cookie
}

func main() {
 http.HandleFunc("/", index)
 http.HandleFunc("/setcookie", makeCookie)
 err := http.ListenAndServe(":9090", nil)
 if err != nil {
  log.Fatal("ListenAndServe ERROR: ", err)
 }
}

沒有留言:

張貼留言

© Mac Taylor, 歡迎自由轉貼。
Background Email Pattern by Toby Elliott
Since 2014