douhuibo5635 2018-03-27 09:49
浏览 418
已采纳

如何全局设置cookiejar,以便在每个http.Client请求中都存在cookie

I am new here and a bit confused with setting cookie jar gloabally. I am using cookiejar from the http package and this is my implementation from other docs available in setting the cookies as jar in http.Client.

    jar, _ := cookiejar.New(nil)
    client := &http.Client{
      Jar: jar,
    }
    req, _ := http.NewRequest("GET", request_url, nil)
    q := req.URL.Query()
    q.Add("authtoken", token)
    req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
    req.URL.RawQuery = q.Encode()
    res, _ := client.Do(req)
    defer res.Body.Close() 
    fmt.Println(res.Cookies()) // can see the cookies here

What I am trying to achieve here is to have this declared gloabally so that once the jar is set the subsequent client request will have the cookies. If I place it in any other function it gets sets to nil again.

    jar, _ := cookiejar.New(nil)
    client := &http.Client{
      Jar: jar,
    }

Any best practise available in how to do this? Thank you.

  • 写回答

2条回答 默认 最新

  • duanchu2607 2018-03-27 10:01
    关注

    http.Client is designed to be reused:

    The Client's Transport typically has internal state (cached TCP connections), so Clients should be reused instead of created as needed. Clients are safe for concurrent use by multiple goroutines.

    So simply just create / configure an http.Client, and reuse it everywhere where you want your cookiejar to work.

    If one configured http.Client doesn't fit all your use cases, then create as many clients that do. To ensure the same cookiejar is used, you may create a client "factory" function which ensures the returned http.Client will have the Jar set.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记