在go语言开发中对于cookie设置方法有两种:
一、通过ResponseWriter设置cookie
func Cookie(w http.ResponseWriter, r *http.Request) {
ck := &http.Cookie{
Name: "myCookie",
Value: "hello",
Path: "/",
Domain: "localhost",
MaxAge: 120,
}
http.SetCookie(w, ck)
ck2, err := r.Cookie("myCookie")
if err != nil {
io.WriteString(w, err.Error())
return
}
io.WriteString(w, ck2.Value)
}
output:hello
这种方法的弊端是第一次读取不到cookie(在response中,需要重定向才可以获取到),需要刷新一次
二、通过header设置cookie
func Cookie2(w http.ResponseWriter, r *http.Request) {
ck := &http.Cookie{
Name: "myCookie",
Value: "hello world",
Path: "/",
Domain: "localhost",
MaxAge: 120,
}
w.Header().Set("Set-Cookie", strings.Replace(ck.String(), " ", "%20", -1))
ck2, err := r.Cookie("myCookie")
if err != nil {
io.WriteString(w, err.Error())
return
}
io.WriteString(w, ck2.Value)
}
注意:value值中不允许有空格符的存在,所以在设置中需要处理下。
调用
import (
"io"
"net/http"
"strings"
)
func main() {
http.HandleFunc("/", Cookie)
http.HandleFunc("/2", Cookie2)
http.ListenAndServe(":8081", nil)
}