Convert curl to Go net/http
Convert curl commands to Go using the net/http standard library. Learn idiomatic Go HTTP patterns for requests, responses, and error handling in detail.
Go
Detailed Explanation
Converting curl to Go net/http
Go's standard library net/http package is powerful enough for most HTTP tasks without any third-party dependencies. Converting curl to Go requires understanding Go's explicit error handling and io.Reader patterns.
GET Request
curl:
curl https://api.example.com/users
Go:
resp, err := http.Get("https://api.example.com/users")
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(body))
POST with JSON
curl:
curl -X POST https://api.example.com/users \
-H "Content-Type: application/json" \
-d '{"name": "Alice"}'
Go:
payload := strings.NewReader(`{"name": "Alice"}`)
req, err := http.NewRequest("POST", "https://api.example.com/users", payload)
if err != nil {
log.Fatal(err)
}
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
Custom Headers
req, _ := http.NewRequest("GET", "https://api.example.com/me", nil)
req.Header.Set("Authorization", "Bearer token123")
req.Header.Set("Accept", "application/json")
Timeout and Transport Configuration
curl:
curl --connect-timeout 5 --max-time 30 https://api.example.com/data
Go:
client := &http.Client{
Timeout: 30 * time.Second,
}
Key Patterns in Go
- Always
defer resp.Body.Close()to prevent resource leaks - Use
http.NewRequestfor full control over method, headers, and body - Use
json.NewEncoderandjson.NewDecoderfor structured data - Handle errors explicitly at every step, as Go does not have exceptions
- Use
context.WithTimeoutfor request-scoped cancellation
Go's net/http is verbose compared to curl but gives you explicit control over every aspect of the HTTP lifecycle, making it ideal for production services where reliability matters.
Use Case
A Go developer building a microservice needs to translate API curl examples from documentation into idiomatic Go code using only the standard library.