HTTP Client
Simple HTTP client with retry logic and timeout support
Description
An HTTP client wrapper with built-in retry logic, timeout handling, and error management. Simplifies common HTTP operations.
Features
- GET/POST/PUT/DELETE methods
- Automatic retries
- Timeout configuration
- Header management
Code
package httpclientimport ( "bytes" "io" "net/http" "time")type Client struct { client *http.Client maxRetries int retryDelay time.Duration}func NewClient(timeout time.Duration, maxRetries int, retryDelay time.Duration) *Client { return &Client{ client: &http.Client{ Timeout: timeout, }, maxRetries: maxRetries, retryDelay: retryDelay, }}func (c *Client) Get(url string, headers map[string]string) (*http.Response, error) { req, err := http.NewRequest("GET", url, nil) if err != nil { return nil, err } return c.doWithRetry(req, headers)}func (c *Client) Post(url string, body []byte, headers map[string]string) (*http.Response, error) { req, err := http.NewRequest("POST", url, bytes.NewBuffer(body)) if err != nil { return nil, err } return c.doWithRetry(req, headers)}func (c *Client) doWithRetry(req *http.Request, headers map[string]string) (*http.Response, error) { for k, v := range headers { req.Header.Set(k, v) } var lastErr error for i := 0; i <= c.maxRetries; i++ { resp, err := c.client.Do(req) if err == nil && resp.StatusCode < 500 { return resp, nil } if resp != nil { resp.Body.Close() } lastErr = err if i < c.maxRetries { time.Sleep(c.retryDelay) } } return nil, lastErr}
package mainimport ( "fmt" "io" "time" "httpclient")func main() { client := httpclient.NewClient( 10*time.Second, 3, 1*time.Second, ) headers := map[string]string{ "Content-Type": "application/json", "Authorization": "Bearer your-token-here", } resp, err := client.Get("https://api.example.com/data", headers) if err != nil { fmt.Printf("Error: %v\n", err) return } defer resp.Body.Close() body, _ := io.ReadAll(resp.Body) fmt.Printf("Status: %d\n", resp.StatusCode) fmt.Printf("Body: %s\n", body)}
Comments
No comments yet. Be the first to comment!
Please login to leave a comment.