英文:
Set context to request when the later is initialised with a url.URL
问题
我想创建一个 net/url.URL
,然后在 http.Client
和 http.Request
结构中使用它,如下所示:
client := http.Client{
Timeout: 5 * time.Second,
}
req := http.Request{
URL: someKindOf_url.URL_type_I_have_already_initialised_elsewhere,
}
resp, err := client.Do(&req)
在构建 req
时,我想传递一个(已经存在的)context.Context
。
Request
类型 似乎没有这样的字段。
有这个 NewRequestWithContext
工厂 函数,但它使用一个字符串而不是 net/url.URL
。
有没有办法解决这个问题?
英文:
I want to create a net/url.URL
and then use it in http.Client
and http.Request
constructs as follows
client := http.Client{
Timeout: 5 * time.Second,
}
req := http.Request{
URL: someKindOf_url.URL_type_I_have_already_initialised_elsewhere,
}
resp, err := client.Do(&req)
Upon req
construction, I want to pass an (already existing) context.Context
The Request
type does not seem to have such a field.
There is this NewRequestWithContext
factory function, but uses a string for the URL
and not a net/url.URL
Is there a way around this?
答案1
得分: 3
你永远不应该使用字面值创建一个http.Request
对象。应该始终使用构造函数NewRequest
或NewRequestWithContext
。构造函数做了很多事情,不仅仅是将简单的值分配给一个结构体。
考虑到这一点,实现你的目标的正确方式是,例如:
req := http.NewRequestWithContext(ctx, http.MethodGet, someKindOf_url.String(), nil)
也可以将上下文分配给现有的请求:
req = req.WithContext(ctx)
英文:
You should never create an http.Request
object with a literal. Always use the constructor functions NewRequest
or NewRequestWithContext
. The constructor does a lot more than simply assigning simple values to a struct.
With this in mind, the correct way to achieve your goal would be, for example:
req := http.NewRequestWithContext(ctx, http.MethodGet, someKindOf_url.String(), nil)
That said, you can assign a context to an existing request:
req = req.WithContext(ctx)
答案2
得分: 0
http.Request
没有公共的context
字段,但是有一个私有的context
字段。
你可以使用http.Request
的WithContext(ctx context.Context)
方法来实现。
英文:
http.Request
doen't have a public context field, but have it private.
What you can do is use WithContext(ctx context.Context)
method of http.Request
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论