Go 使用fasthttp库保存维护会话的Cookie
我最近一直很紧张,我需要找到一种方法,在向URI发送post请求后保存cookies,这样我就可以向其他端点发送请求并维护该会话。我正在尝试将项目添加到购物车,但如果不保存cookies,购物车将为空。(购物车)我目前正在使用此功能处理cookies,但似乎没有将cookies转发到下一个请求:Go 使用fasthttp库保存维护会话的Cookie,go,fasthttp,Go,Fasthttp,我最近一直很紧张,我需要找到一种方法,在向URI发送post请求后保存cookies,这样我就可以向其他端点发送请求并维护该会话。我正在尝试将项目添加到购物车,但如果不保存cookies,购物车将为空。(购物车)我目前正在使用此功能处理cookies,但似乎没有将cookies转发到下一个请求: func (c *CookieClient) Do(req *fasthttp.Request, resp *fasthttp.Response) error { for { zap.S().I
func (c *CookieClient) Do(req *fasthttp.Request, resp *fasthttp.Response) error {
for {
zap.S().Info("Saving Cookie")
if err := c.Client.Do(req, resp); err != nil {
return err
}
statusCode := resp.Header.StatusCode()
if statusCode != fasthttp.StatusMovedPermanently &&
statusCode != fasthttp.StatusFound &&
statusCode != fasthttp.StatusSeeOther &&
statusCode != fasthttp.StatusTemporaryRedirect &&
statusCode != fasthttp.StatusPermanentRedirect {
break
}
location := resp.Header.PeekBytes(strLocation)
if len(location) == 0 {
return fmt.Errorf("Redirect with missing Location header")
}
u := req.URI()
u.UpdateBytes(location)
resp.Header.VisitAllCookie(func(key, value []byte) {
c := fasthttp.AcquireCookie()
defer fasthttp.ReleaseCookie(c)
c.ParseBytes(value)
if expire := c.Expire(); expire != fasthttp.CookieExpireUnlimited && expire.Before(time.Now()) {
zap.S().Info("Deleting Expired Cookie")
req.Header.DelCookieBytes(key)
} else {
req.Header.SetCookieBytesKV(key, c.Value())
}
})
}
return nil
}作者可能有一个有效的方法: 您可以使用以下方法检索cookie,然后可以将其重新分配给另一个请求
func ParseTokenFromRequest(ctx*fasthttp.RequestCtx)字符串{
token:=string(ctx.Request.Header.Cookie(“GoLog-token”)//GoLog-token是Cookie的硬编码名称
返回令牌
}
然后,您可以使用已检索到的值创建cookie:
//返回cookie值作为输入的CreateCookie方法(GoLog令牌作为键)
func CreateCookie(键字符串、值字符串、过期整数)*fasthttp.Cookie{
if strings.Compare(键“”)=0{
key=“GoLog令牌”
}
调试(“CreateCookie | Creating Cookie | Key:,Key,| Val:,value”)
authCookie:=fasthttp.Cookie{}
authCookie.SetKey(key)
authCookie.SetValue(值)
authCookie.SetMaxAge(过期)
authCookie.SetHTTPOnly(true)
authCookie.SetSameSite(fasthttp.CookieSameSiteLaxMode)
返回并验证cookie
}
然后,您可以转发cookie或将其保存到(可能在内存中)db中:
authcookie:=CreateCookie(“GoLog令牌”,令牌,cfg.Redis.Token.Expire)
ctx.Response.Header.SetCookie(authcookie)
//把饼干放在这里
询问fasthttp的作者。