英文:
How to send same cookies (CookieJar) in http.Client for different domains
问题
我正在使用http.Client
来进行一些生产资源的HTTP请求。
这个资源有两个不同的域名,但具有相同的业务逻辑(例如:example.com,instance.com)。因此,example.com的所有cookie对于instance.com也是有效的。
问题是我需要将相同的cookie发送到两个不同的域名,但在GoLang中是不可能的。
func (*Jar) Cookies
会返回特定域名的URL的cookie,所以我必须调用一些准备cookie的函数:
func (session *Session) PrepareCookiesForExample() {
example, _ := url.Parse("https://example.com")
session.client.Jar.SetCookies(example, session.client.Jar.Cookies(commu))
}
因此,我必须在每个请求中调用这个函数,这非常不方便,如果我忘记调用这个函数,可能会导致错误(因为cookie没有被发送)。
如何使用CookieJar为所有域名发送相同的cookie?
英文:
I'm using http.Client
for making HTTP requests for some production resource.
> This resource has two different domains with the same business-logic
> (for example: example.com, instance.com). So ALL cookies for example.com is valid for instance.com and so.
The problem is that I need to send same cookies to two different domains, that is not possible in GoLang.
func (*Jar) Cookies
returns cookies for url with a specific domain, so I must call some cookies-preparation function:
func (session *Session) PrepareCookiesForExample() {
example, _ := url.Parse("https://example.com")
session.client.Jar.SetCookies(example, session.client.Jar.Cookies(commu))
}
So I have to call this function in my each request that is pretty uncomfortable and can cause errors (because cookies are not sent) if I forget to call this fuction.
> How to send the same cookies for ALL domains by using CookieJar?
答案1
得分: 1
首先,提醒一下,将Cookie限制在设置它们的域名下是一项重要的安全功能,不应该轻易绕过。
以下是创建自己的Cookie Jar的示例代码:
package main
import (
"net/http"
"net/url"
)
type SharedCookieJar struct {
CookieSlice []*http.Cookie
}
func (jar *SharedCookieJar) SetCookies(u *url.URL, cookies []*http.Cookie) {
jar.CookieSlice = append(jar.CookieSlice, cookies...)
}
func (jar *SharedCookieJar) Cookies(u *url.URL) []*http.Cookie {
return jar.CookieSlice
}
func main() {
c := http.Client{
Jar: &SharedCookieJar{},
}
c.Get("https://example.com/")
c.Get("https://instance.com/") // 将使用example.com设置的Cookie
}
更多关于接口的信息可以在这里阅读:https://tour.golang.org/methods/9
英文:
First of all, a reminder that restricting cookies to the domains they were set from is an important security feature that should not be bypassed lightly.
Here is an example of how you'd create your own cookie Jar:
package main
import (
"net/http"
"net/url"
)
type SharedCookieJar struct {
CookieSlice []*http.Cookie
}
func (jar *SharedCookieJar) SetCookies(u *url.URL, cookies []*http.Cookie) {
jar.CookieSlice = append(jar.CookieSlice, cookies...)
}
func (jar *SharedCookieJar) Cookies(u *url.URL) []*http.Cookie {
return jar.CookieSlice
}
func main() {
c := http.Client{
Jar:&SharedCookieJar{},
}
c.Get("https://example.com/")
c.Get("https://instance.com/") // will use cookies set by example.com
}
Further reading on interfaces here: https://tour.golang.org/methods/9
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论