Package ctxhttp provides helper functions for performing context-aware HTTP requests.
import "golang.org/x/net/context/ctxhttp"// Do sends an HTTP request with the provided http.Client and returns an HTTP response
func Do(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error)
// Get issues a GET request via the Do function
func Get(ctx context.Context, client *http.Client, url string) (*http.Response, error)
// Head issues a HEAD request via the Do function
func Head(ctx context.Context, client *http.Client, url string) (*http.Response, error)
// Post issues a POST request via the Do function
func Post(ctx context.Context, client *http.Client, url string, bodyType string, body io.Reader) (*http.Response, error)
// PostForm issues a POST request via the Do function
func PostForm(ctx context.Context, client *http.Client, url string, data url.Values) (*http.Response, error)Do sends an HTTP request with the provided http.Client and returns an HTTP response.
If the client is nil, http.DefaultClient is used.
The provided ctx must be non-nil. If it is canceled or times out, ctx.Err() will be returned.
Get issues a GET request via the Do function.
Head issues a HEAD request via the Do function.
Post issues a POST request via the Do function.
PostForm issues a POST request via the Do function.
import (
"context"
"fmt"
"golang.org/x/net/context/ctxhttp"
"net/http"
"time"
)
func fetchWithTimeout(url string) error {
// Create context with timeout
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// Make GET request with context
resp, err := ctxhttp.Get(ctx, nil, url)
if err != nil {
return err
}
defer resp.Body.Close()
fmt.Println("Status:", resp.Status)
return nil
}func postData(url string, data io.Reader) error {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
resp, err := ctxhttp.Post(ctx, nil, url, "application/json", data)
if err != nil {
return err
}
defer resp.Body.Close()
return nil
}func fetchWithCustomClient(url string) error {
client := &http.Client{
Timeout: 30 * time.Second,
}
ctx := context.Background()
resp, err := ctxhttp.Get(ctx, client, url)
if err != nil {
return err
}
defer resp.Body.Close()
return nil
}