Go by Example

HTTP Client

Send web requests with a reusable client, a timeout and clear response checks.

HTTP is the set of rules web programs use to exchange requests and responses. The net/http package includes a client that sends requests to servers. Reuse an http.Client to save the setup work of opening new connections, and set a timeout so a request cannot wait forever.

Use a request context, a value carrying a stop signal, when the caller may need to cancel one request. Set a client timeout to limit the full exchange. Close the response body, the data sent back by the server, when finished reading it.

package main
 
import (
    "context"
    "fmt"
    "io"
    "net/http"
    "time"
)
 
func main() {
    client := &http.Client{Timeout: 5 * time.Second}
    ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
    defer cancel()
 
    req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://example.com", nil)
    if err != nil {
        panic(err)
    }
    resp, err := client.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()
    body, err := io.ReadAll(resp.Body)
    if err != nil {
        panic(err)
    }
    fmt.Println(resp.StatusCode, len(body))
}

In production

http.Get uses a client without an overall timeout. Limit how much response data you read from a server you do not control. Read the whole body and close it so Go can reuse the connection. Check the response status code yourself: a server can reply with an error code such as 404, meaning โ€œnot found,โ€ and http.Get still returns a response.

Enjoyed this? Get more software craft delivered to your inbox.