如何在Golang中通过response.Cookies()获取指定名称的单个cookie?

huangapple go评论117阅读模式
英文:

How to get a single cookie by name from response.Cookies() in Golang?

问题

response.Cookies()中获取特定名称的cookie有没有办法呢?

假设我需要从下面的cookie jar中获取名为wr_entry_path的cookie。
[wr_entry_path=/aP3Mk1i6M/xcp0g1/vMg/Qpr7ccN0OE3p/YxU3A31SAw/RWoGdE/k2DyQ; Path=/; Expires=Tue, 19 Apr 2022 19:40:03 GMT waitingroom=1650392103~id=072e61d9e7fa58639a6a2af28cea89de; Path=/; HttpOnly; Secure; SameSite=None]

任何帮助都将不胜感激!

英文:

Is there a way how to get only one cookie by name from response.Cookies()?

Let's say that I need the wr_entry_path cookie from this cookie jar down below.
[wr_entry_path=/aP3Mk1i6M/xcp0g1/vMg/Qpr7ccN0OE3p/YxU3A31SAw/RWoGdE/k2DyQ; Path=/; Expires=Tue, 19 Apr 2022 19:40:03 GMT waitingroom=1650392103~id=072e61d9e7fa58639a6a2af28cea89de; Path=/; HttpOnly; Secure; SameSite=None]

Any help appreciated!!

答案1

得分: 1

Response.Cookies() 返回一个包含所有解析过的 http.Cookie 的切片。只需使用循环遍历它,并找到具有所需名称的那个:

  1. cookies := resp.Cookies()
  2. for _, c := range cookies {
  3. if c.Name == "wr_entry_path" {
  4. // 找到了!使用它!
  5. fmt.Println(c.Value) // cookie 的值
  6. }
  7. }
英文:

Response.Cookies() returns you a slice of all parsed http.Cookies. Simply use a loop to iterate over it and find the one that has the name you're looking for:

  1. cookies := resp.Cookies()
  2. for _, c := range cookies {
  3. if c.Name == "wr_entry_path" {
  4. // Found! Use it!
  5. fmt.Println(c.Value) // The cookie's value
  6. }
  7. }

huangapple
  • 本文由 发表于 2022年4月20日 02:07:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/71929414.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定