Go 设置 cookie
Go 语言中通过 net/http 包中的 SetCookie 来设置:
http.SetCookie(w ResponseWriter, cookie *Cookie)
w 表示需要写入的 response,cookie 是一个 struct,让我们来看一下 cookie 对象是怎么样
的
type Cookie struct {
Name string
Value string
Path string
Domain string
Expires time.Time
RawExpires string
// 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
}
我们来看一个例子,如何设置 cookie
expiration := *time.LocalTime()
expiration.Year += 1
cookie := http.Cookie{Name: "username", Value: "astaxie", Expires: expiration}
http.SetCookie(w, &cookie)