pkaramol
pkaramol

Reputation: 19322

Set context to request when the later is initialised with a 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?

Upvotes: 0

Views: 755

Answers (2)

Oleg Butuzov
Oleg Butuzov

Reputation: 5395

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

Upvotes: 0

Jonathan Hall
Jonathan Hall

Reputation: 79546

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)

Upvotes: 3

Related Questions