首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Go中创建HTTP会话

如何在Go中创建HTTP会话
EN

Stack Overflow用户
提问于 2020-02-06 01:10:16
回答 1查看 1.3K关注 0票数 0

我目前正在使用fasthttp发送我的请求,我的问题是,是否有一种方法可以有一个持久的会话?我需要饼干和数据。

c := fasthttp.Client{ Name: "Add To Cart",}

代码语言:javascript
复制
store, err := session.Start() // ?????
args := fasthttp.AcquireArgs()
defer fasthttp.ReleaseArgs(args)

args.Add("pid", sizepid)
args.Add("options", "[]")
args.Add("quantity", "1")

statusCode, body, err := c.Post(nil, "URL", args)
if err != nil {
    panic(err)
}`
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-02-06 10:49:44

基于您的问题,我认为这一点对您来说已经很清楚了,但是以防万一:会话不是在客户机上启动的,而是在服务器上启动的。服务器检查特定cookie是否存在;如果存在,则恢复cookie标识的会话;如果不存在,则创建一个新会话,并将标识符作为cookie发送回客户端。客户端所需要做的就是将正确的cookie发送到服务器。

所以,你需要读和写饼干。fasthttp.Client.Post()接口不允许您这样做。所以,不是那种很好的界面,事情变得相当丑陋。

在执行请求之前,您需要向fasthttp请求一个RequestResponse对象。完成初始请求后,您需要查看所有cookie,或者读取特定的cookie。现在,您可以在下一个请求中使用这些值。

我写了一个简短的例子来说明你会怎么做。

代码语言:javascript
复制
func main() {
    c := fasthttp.Client{}

    // Create a request
    req := fasthttp.AcquireRequest()
    defer fasthttp.ReleaseRequest(req)
    req.SetRequestURI(`https://www.google.com/`)

    // Create a response
    resp := fasthttp.AcquireResponse()
    defer fasthttp.ReleaseResponse(resp)

    // Execute the request, writing to the response object
    err := c.Do(req, resp)
    if err != nil {
        panic(err)
    }

    //  Loop over all cookies; usefull if you want to just send everything back on consecutive requests
    resp.Header.VisitAllCookie(func(key, value []byte) {
        log.Printf("Cookie %s: %s\n", key, value)
    })

    // Read a specific cookie
    nid := fasthttp.AcquireCookie()
    defer fasthttp.ReleaseCookie(nid)
    nid.SetKey(`NID`)
    if resp.Header.Cookie(nid) {
        log.Println("Value for NID Cookie: " + string(nid.Value()))

        // Create a second request and set the cookie from the first
        req2 := fasthttp.AcquireRequest()
        defer fasthttp.ReleaseRequest(req2)
        req2.SetRequestURI(`https://www.google.com/`)
        req2.Header.SetCookie(`NID`, string(nid.Value()))

        // Now you can execute this request again using c.Do() - don't forget to acquire a new Response!
    }
}

注意:您可以选择跳过fasthttp.AcquireXXX()defer fasthttp.ReleaseXXX(yyy)步骤--但这将大大抵消(可能是大多数)比使用标准net/http带来的性能好处,因此,如果您选择这条路线,可能会把fasthttp放在一起。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60086343

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档