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

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

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 的切片。只需使用循环遍历它,并找到具有所需名称的那个:

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

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:

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

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:

确定