zhttp.go 1.15 KB
Newer Older
Vladimir Barsukov's avatar
zhttp  
Vladimir Barsukov committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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)
			}
Vladimir Barsukov's avatar
lint    
Vladimir Barsukov committed
34

Vladimir Barsukov's avatar
zhttp  
Vladimir Barsukov committed
35
36
			continue
		}
Vladimir Barsukov's avatar
lint    
Vladimir Barsukov committed
37

Vladimir Barsukov's avatar
zhttp  
Vladimir Barsukov committed
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
		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)
}

Vladimir Barsukov's avatar
lint    
Vladimir Barsukov committed
60
func (c *ZClient) GetJSON(target any, url string) error {
Vladimir Barsukov's avatar
zhttp  
Vladimir Barsukov committed
61
62
63
64
65
66
67
68
69
70
	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)
}