How to Use HTTP Client in Go: Simple Guide with Examples
In Go, you use the
http.Client type to send HTTP requests and receive responses. You create a client, build a request with http.NewRequest, then call client.Do(request) to get the response. Always close the response body to avoid resource leaks.Syntax
The basic syntax to use the HTTP client in Go involves creating a client, making a request, and handling the response.
- http.Client: The client used to send requests.
- http.NewRequest: Creates a new HTTP request.
- client.Do: Sends the request and returns the response.
- resp.Body.Close(): Closes the response body to free resources.
go
client := &http.Client{}
req, err := http.NewRequest("GET", "https://example.com", nil)
if err != nil {
// handle error
}
resp, err := client.Do(req)
if err != nil {
// handle error
}
defer resp.Body.Close()
// read resp.Body hereExample
This example shows how to send a GET request to fetch data from a website and print the response status and body.
go
package main import ( "fmt" "io" "net/http" ) func main() { client := &http.Client{} req, err := http.NewRequest("GET", "https://httpbin.org/get", nil) if err != nil { fmt.Println("Error creating request:", err) return } resp, err := client.Do(req) if err != nil { fmt.Println("Error sending request:", err) return } defer resp.Body.Close() fmt.Println("Response Status:", resp.Status) body, err := io.ReadAll(resp.Body) if err != nil { fmt.Println("Error reading body:", err) return } fmt.Println("Response Body:", string(body)) }
Output
Response Status: 200 OK
Response Body: {
"args": {},
"headers": {
"Accept-Encoding": "gzip",
"Host": "httpbin.org",
"User-Agent": "Go-http-client/1.1"
},
"origin": "...",
"url": "https://httpbin.org/get"
}
Common Pitfalls
Common mistakes when using the HTTP client in Go include:
- Not closing the response body, which causes resource leaks.
- Ignoring errors from
http.NewRequestorclient.Do. - Using
http.Getfor complex requests instead ofhttp.Clientandhttp.NewRequest.
go
/* Wrong way: Not closing response body */ resp, err := http.Get("https://example.com") if err != nil { // handle error } // Forgot resp.Body.Close() /* Right way: Closing response body */ resp, err := http.Get("https://example.com") if err != nil { // handle error } defer resp.Body.Close()
Quick Reference
Remember these key points when using the HTTP client in Go:
- Always create requests with
http.NewRequestfor flexibility. - Use
client.Doto send requests. - Always
defer resp.Body.Close()after getting a response. - Check errors after every step.
Key Takeaways
Use http.Client with http.NewRequest and client.Do to send HTTP requests.
Always close the response body with defer resp.Body.Close() to avoid leaks.
Check errors after creating requests and sending them.
Use http.Client for more control instead of http.Get for simple requests.
Read the response body with io.ReadAll or similar methods after getting the response.