Making HTTP calls
The Go standard library offers two basic ways of issuing HTTP calls to interact with websites and web services: if you do not need to configure timeouts, transport properties, or redirect policies, simply use the shared client. If you need to do additional configuration, use http.Client. This recipe demonstrates both.
How to do it...
- The standard library includes a shared HTTP client. You can use that to interact with web servers using the default configuration:
response, err := http.Get("http://example.com") if err!=nil { Â Â // Handle error } // Always close response body defer response.Body.Close() if response.StatusCode/100==2 { Â Â // HTTP 2xx, call was successful. Â Â // Work with response.Body } - If you need to apply different timeout values, change the redirect policy, or configure the transport, create a new
http.Client, initialize it, and use that:client:=http.Client{ Â Â // Set a timeout for all outgoing...