cookie是一种存储在客户端的、体积较小的信息,由服务器通过HTTP响应报文发送的。cookie的设计本意是要克服HTTP的无状态。cookie基本可以分类为会话cookie和持久cookie。
Go语言里面Cookie结构表示:
type Cookie struct {
Name string
Value string
Path string // optional
Domain string // optional
Expires time.Time // optional
RawExpires string // for reading cookies only
// MaxAge=0 means no 'Max-Age' attribute specified.
// MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'
// MaxAge>0 means Max-Age attribute present and given in seconds
MaxAge int
Secure bool
HttpOnly bool
Raw string
Unparsed []string // Raw text of unparsed attribute-value pairs
}
没有设置Expires字段的cookie通话称为回话cookie或临时cookie,这种cookie在浏览器关闭时自动移除。设置Expires字段的cookie称为持久cookie。Expires和MaxAge都可以设置cookie过期时间,MaxAge是指创建后存活多少秒,Expires是指什么时候过期。为让浏览器正常运行,只使用Expires或Expires和MaxAge共同使用。
发送,获取cookie:
//发送cookie
func setCo(w http.ResponseWriter, r *http.Request) {
c1 := http.Cookie{
Name: "first_cookie",
Value: "z",
HttpOnly: true,
}
c2 := http.Cookie{
Name: "second_cookie",
Value: "zb",
HttpOnly: true,
}
w.Header().Set("Set-Cookie", c1.String())
w.Header().Add("Set-Cookie", c2.String())
}
//快捷方法
func fastSC(w http.ResponseWriter, r *http.Request) {
c1 := http.Cookie{
Name: "first_cookie",
Value: "z",
HttpOnly: true,
}
c2 := http.Cookie{
Name: "second_cookie",
Value: "zb",
HttpOnly: true,
}
http.SetCookie(w, &c1)
http.SetCookie(w, &c2)
}
//获取cookie,返回值是字符串分片
func getCookie(w http.ResponseWriter, r *http.Request) {
h := r.Header["Cookie"]
fmt.Fprintln(w, h)
}
//快捷方法,c是cookie对象,cs是[]*Cookie
func fastGC(w http.ResponseWriter, r *http.Request) {
c, err := r.Cookie("first_cookie")
if err != nil {
return
}
cs := r.Cookies()
fmt.Fprintln(w, cs)
}
func main() {
http.HandleFunc("/cookie", setCo)
http.HandleFunc("/getcookie", fastGC)
http.ListenAndServe("127.0.0.1:8080", nil)
}
对消息使用Base64URL编码:
若cookie的值包含空格、百分号等特殊字符,需要进行编码。通常都需要编码。
func setMessage(w http.ResponseWriter, r *http.Request) {
msg := []byte(`你 好 +++ === --- \\\\ !`)
cookie := http.Cookie{
Name: "hi",
Value: base64.URLEncoding.EncodeToString(msg),
}
http.SetCookie(w, &cookie)
}
func showMseeage(w http.ResponseWriter, r *http.Request) {
c, err := r.Cookie("hi")
if err != nil {
if err == http.ErrNoCookie {
fmt.Fprintln(w, "no cookie")
}
} else {
rc := http.Cookie{
Name: "hi",
MaxAge: -1,
Expires: time.Unix(1, 0),
}
http.SetCookie(w, &rc)
val, _ := base64.URLEncoding.DecodeString(c.Value)
fmt.Fprintln(w, string(val))
}
}
func main() {
http.HandleFunc("/setc", setMessage)
http.HandleFunc("/showc", showMseeage)
http.ListenAndServe("127.0.0.1:8080", nil)
}