httpgorequestgo-context

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?


Solution

  • 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)