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