Use the standard library's net/http package for most cases, as it provides a robust, dependency-free client with built-in support for timeouts and TLS. For quick scripts or complex scenarios like automatic retries, consider third-party libraries like golang.org/x/net/http2 or github.com/go-resty/resty, but the standard http.Client is sufficient for 95% of production needs.
Here is the standard pattern using http.Get for simple requests and http.Client with a custom Request for more control:
package main
import (
"fmt"
"io"
"net/http"
"time"
)
func main() {
// 1. Simple GET request (no timeout control)
resp, err := http.Get("https://api.example.com/data")
if err != nil {
panic(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
panic("unexpected status code")
}
body, _ := io.ReadAll(resp.Body)
fmt.Println("Simple GET:", string(body))
// 2. Robust request with timeout and custom headers
client := &http.Client{
Timeout: 5 * time.Second,
}
req, err := http.NewRequest("POST", "https://api.example.com/submit",
[]byte(`{"key":"value"}`))
if err != nil {
panic(err)
}
req.Header.Set("Content-Type", "application/json")
resp, err = client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, _ = io.ReadAll(resp.Body)
fmt.Println("POST response:", string(body))
}
For command-line testing or quick verification without writing Go code, use curl with the -X flag for the method and -d for the body:
# GET request
curl -s https://api.example.com/data
# POST request with JSON body and custom header
curl -X POST https://api.example.com/submit \
-H "Content-Type: application/json" \
-d '{"key":"value"}'
Always remember to close the response body (defer resp.Body.Close()) to prevent resource leaks, and prefer creating a dedicated http.Client with a configured Timeout over using http.Get or http.Post convenience functions in production. The convenience functions use a global client with no timeout, which can cause your application to hang indefinitely if the server is unresponsive. If you need to share a client across multiple goroutines, create a single http.Client instance at the package level; it is safe for concurrent use.