Commit 8fc95b40 authored by Vladimir Barsukov's avatar Vladimir Barsukov
Browse files

zhttp

parent 2a9b9ae7
package zhttp
import (
"encoding/json"
"fmt"
"net/http"
"time"
)
var DefaultClient = &http.Client{Timeout: time.Second * 10}
type ZClient struct {
httpClient *http.Client
}
type Config struct {
Repit int
}
func New(c *http.Client) *ZClient {
return &ZClient{httpClient: c}
}
func Default() *ZClient {
return New(DefaultClient)
}
func (c *ZClient) Do(r *http.Request, try int, sleepDur time.Duration) (resp *http.Response, err error) {
for i := 0; i < try; i++ {
if resp, err = c.httpClient.Do(r); err != nil {
if i+1 < try {
time.Sleep(sleepDur)
}
continue
}
break
}
return
}
func (c *ZClient) GetEmpty(url string) error {
var err error
var resp *http.Response
if resp, err = c.httpClient.Get(url); err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
return nil
}
return fmt.Errorf("status code: %v", resp.StatusCode)
}
func (c *ZClient) GetJson(target any, url string) error {
var err error
var resp *http.Response
if resp, err = c.httpClient.Get(url); err != nil {
return err
}
defer resp.Body.Close()
return json.NewDecoder(resp.Body).Decode(&target)
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment