-1

我最近一直在拔头发,我需要找到一种在向 URI 发送请求后保存 cookie 的方法,以便我可以将请求发送到其他端点并维护该会话。我正在尝试将商品添加到购物车,但不保存 cookie,购物车将为空。(购物车)我目前正在使用它来处理 cookie,但似乎没有将 cookie 转发到下一个请求:

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

}

4

1 回答 1

0

可能作者可以有一个有效的方法:

您可以使用以下方法检索 cookie,然后您可以将其重新分配给另一个请求。

func ParseTokenFromRequest(ctx *fasthttp.RequestCtx) string {
    token := string(ctx.Request.Header.Cookie("GoLog-Token")) // GoLog-Token is the hardcoded name of the cookie
    return token
}

然后您可以使用已检索到的值创建 cookie:

//CreateCookie Method that return a cookie valorized as input (GoLog-Token as key)
func CreateCookie(key string, value string, expire int) *fasthttp.Cookie {
    if strings.Compare(key, "") == 0 {
        key = "GoLog-Token"
    }
    log.Debug("CreateCookie | Creating Cookie | Key: ", key, " | Val: ", value)
    authCookie := fasthttp.Cookie{}
    authCookie.SetKey(key)
    authCookie.SetValue(value)
    authCookie.SetMaxAge(expire)
    authCookie.SetHTTPOnly(true)
    authCookie.SetSameSite(fasthttp.CookieSameSiteLaxMode)
    return &authCookie
}

然后您可以转发 cookie 或将其保存到(可能在内存中)数据库中:

authcookie := CreateCookie("GoLog-Token", token, cfg.Redis.Token.Expire)
ctx.Response.Header.SetCookie(authcookie)
// store cookie here
于 2020-02-08T11:29:14.557 回答