ctx.SetCookie("ZJXUSS", res.ZJXUSS, 0, "/", ctx.Request.Host, false, true)

获取cookie

cookie, err := ctx.Cookie("ZJXUSS")

结合源码了解一下http协议里的cookie:

// SetCookie adds a Set-Cookie header to the ResponseWriter's headers.
// The provided cookie must have a valid Name. Invalid cookies may be
// silently dropped.
func (c *Context) SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool) {
    if path == "" {
        path = "/"
    }
    http.SetCookie(c.Writer, &http.Cookie{
        Name:     name,
        Value:    url.QueryEscape(value),
        MaxAge:   maxAge,
        Path:     path,
        Domain:   domain,
        SameSite: c.sameSite,
        Secure:   secure,
        HttpOnly: httpOnly,
    })
}

gin的实际是封装了go的cookie操作http.SetCookie,第二个参数传的cookie的结构:
// A Cookie represents an HTTP cookie as sent in the Set-Cookie header of an
// HTTP response or the Cookie header of an HTTP request.
//
// See https://tools.ietf.org/html/rfc6265 for details.
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
    SameSite SameSite
    Raw      string
    Unparsed []string // Raw text of unparsed attribute-value pairs
}
name、value: 要在cookie保存的键值对
maxAge: max-age,cookie保存时间
 0: 不过期
-1: 不保存
>0: 保存多少秒
domain: 域名
secure: 防止信息传输泄漏
true: 只在https中传输,http不能传输 
false: 可以在https、http中传输
httpOnly: 禁止js读取,防止xss攻击

标签: none

添加新评论