Go语言操作Cookie
GO操作Cookie
在日常开发中,经常会用到Cookie存储一些我们需要的信息。
Cookie参数详解
参数 | 类型 | 含义 |
---|---|---|
Name | string | cookie的名称 |
Value | string | cookie的值;value值中不允许有空格符的存在,建议在设置时处理下 |
Path | string | Cookie的使用路径。如果设置为“/sessionWeb/”,则只有contextPath为“/sessionWeb”的程序可以访问该Cookie。如果设置为“/”,则本域名下contextPath都可以访问该Cookie。注意最后一个字符必须为“/”。 |
Domain | string | 可以访问该Cookie的域名。如果设置为“.google.com”,则所有以“google.com”结尾的域名都可以访问该Cookie。注意第一个字符必须为“.” |
MaxAge | int | 被访问后的存活时间;这个时间是个相对值(比如:3600s);MaxAge=0,未指定该属性;MaxAge<0时,删除cookie,相当于“Max Age:0” |
Expires | time.Time | Expires是cookie的过期时间,如果不设置,那么这是一个session型的cookie,即浏览器会话有用,一旦关闭浏览器,cookie随即会被删除;Expires指定的时间可以是相对文件的最后访问时间(Atime)或者修改时间(MTime);比如2018/10/10 10:10:10 |
RawExpires | string | 仅用于阅读cookies |
0Secure | bool | 是否需要安全传输,为true时只有https才会传输该cookie |
HttpOnly | bool | 为true时,不能通过js读取该cookie的值 |
Raw | string | |
Unparsed | []string | 未解析的 attribute-value 属性位对 |
Cookie的设置、读取、删除
package main
import (
"io"
"net/http"
)
//Cookie1Handler 方式一
func Cookie1Handler(w http.ResponseWriter, r *http.Request) {
ck := &http.Cookie{
Name: "test-name",
Value: "hello",
Path: "/",
Domain: "localhost",
MaxAge: 120,
}
http.SetCookie(w, ck)
cookie, err := r.Cookie("test-name")
if err != nil {
io.WriteString(w, err.Error())
return
}
io.WriteString(w, cookie.Value)
}
//Cookie2Handler 方式二
func Cookie2Handler(w http.ResponseWriter, r *http.Request) {
ck := &http.Cookie{
Name: "test-name2",
Value: "hello2",
Path: "/",
Domain: "localhost",
MaxAge: 120,
}
w.Header().Set("set-cookie", ck.String())
cookie, err := r.Cookie("test-name2")
if err != nil {
io.WriteString(w, err.Error())
return
}
io.WriteString(w, cookie.Value)
}
//CookieClear 删除Cookie
func CookieClear(w http.ResponseWriter, r *http.Request) {
cookie := &http.Cookie{
Name: "test-name",
Value: "",
Path: "/",
Domain: "localhost",
MaxAge: -1,
}
http.SetCookie(w, cookie)
}
func main() {
http.HandleFunc("/cookie", Cookie1Handler)
http.HandleFunc("/cookie2", Cookie2Handler)
http.HandleFunc("/clear", CookieClear)
http.ListenAndServe(":9999", nil)
}