将上下文设置为请求(request),当后者使用url.URL进行初始化时。

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

Set context to request when the later is initialised with a url.URL

问题

我想创建一个 net/url.URL,然后在 http.Clienthttp.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对象。应该始终使用构造函数NewRequestNewRequestWithContext。构造函数做了很多事情,不仅仅是将简单的值分配给一个结构体。

考虑到这一点,实现你的目标的正确方式是,例如:

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.RequestWithContext(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

huangapple
  • 本文由 发表于 2021年8月11日 18:33:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/68740328.html
匿名

发表评论

匿名网友

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

确定