req, err := http.NewRequestWithContext(ctx, "GET", "http://example.com", nil) if err != nil { // handle error } resp, err := http.DefaultClient.Do(req) if err != nil { // handle error } defer resp.Body.Close()
data := url.Values{} data.Set("key", "value") req, err := http.NewRequestWithContext(ctx, "POST", "http://example.com", strings.NewReader(data.Encode())) if err != nil { // handle error } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") resp, err := http.DefaultClient.Do(req) if err != nil { // handle error } defer resp.Body.Close()
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) defer cancel() req, err := http.NewRequestWithContext(ctx, "GET", "http://example.com", nil) if err != nil { // handle error } resp, err := http.DefaultClient.Do(req) if err != nil { if ctx.Err() == context.DeadlineExceeded { // handle timeout error } // handle other errors } defer resp.Body.Close()In this example, a new HTTP GET request is created with a context that has a timeout of 100 milliseconds. If the request takes longer than 100 milliseconds, the context will be canceled and the request will be aborted. If an error occurs while sending the request, the context error will be checked to see if it was due to a timeout. The response from the server is then read and the connection is closed. These examples use the `net/http` package in Go.