Go简单的Cookie 操作
代码示例
package main
import (
"fmt"
"log"
"net/http"
"time"
)
func setCookie(w http.ResponseWriter,r *http.Request) {
expiration := time.Now().Add(time.Hour)
http.SetCookie(w,&http.Cookie{
Name: "access_cookie",
Value: "cookie get test",
Expires: expiration,
HttpOnly: true,
})
redirectURL := "/"
http.Redirect(w,r,redirectURL,200)
}
func getCookie(w http.ResponseWriter,r *http.Request) {
c ,err := r.Cookie("access_cookie")
if err !=nil{
fmt.Fprintf(w,"can not get the cookie %s",err)
log.Fatal(err)
}
tokenString := c.Value
fmt.Fprintln(w,tokenString)
}
func main() {
http.HandleFunc("/setCookie",setCookie)
http.HandleFunc("/getCookie",getCookie)
err := http.ListenAndServe(":8082",nil)
if err !=nil{
fmt.Println("listen and server failed err :",err)
return
}
}

浙公网安备 33010602011771号