ways of doing HTTP requests
suggest changePackage net/http has a layered design where each layer is a convenience wrapper on top of a lower layer.
Each lower layer is more complex but offers more control.
Here’s a recap of 3 ways of doing an HTTP GET request.
Use http.Get() function
The top-level http.Get function is the simplest, but it is not recommended because http.DefaultClient has no timeout.
Use http.Client.Get() method
- create
*http.Clientwith&http.Client{} - set appropriate
Timeout - use its
Get()orPost()orPostForm()methods
Use http.Client.Do() method
This allows the greatest control over the request.
- create
http.Clientand set appropriateTimeout - create a
*http.Requestwithhttp.NewRequestorhttp.NewRequestWithContext - set its
Methodto"GET","POST","HEAD","PUT", or"DELETE" - set custom headers such as
User-AgentwithHeader.Set(key, value string) - set the body to send by assigning
Body, of typeio.ReadCloser - set
TransferEncoding - send the request with
client.Do(req *http.Request) - set a per-request deadline with
req = req.WithContext(ctx), wherectxcarries a deadline or timeout
net/http has no http.Put or http.Delete helper. Build the request and send it with Client.Do, or with http.DefaultClient.Do.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents