-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathclient.go
More file actions
72 lines (61 loc) · 1.51 KB
/
client.go
File metadata and controls
72 lines (61 loc) · 1.51 KB
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package yandex
import (
"encoding/json"
"fmt"
"io"
"net/http"
"time"
)
type Config struct {
BaseURL string
UserAgent string
Timeout time.Duration
Language string // "ru" or "en"
Concurrency int
Interface string // bind outgoing connections to this network interface (SO_BINDTODEVICE, Linux only)
}
type Client struct {
httpClient *http.Client
config *Config
lastTestStart time.Time
}
func NewClient(cfg *Config) *Client {
if cfg.BaseURL == "" {
cfg.BaseURL = "https://yandex.ru/internet"
}
if cfg.UserAgent == "" {
cfg.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
}
if cfg.Timeout == 0 {
cfg.Timeout = 30 * time.Second
}
if cfg.Concurrency <= 0 {
cfg.Concurrency = 4
}
httpClient := &http.Client{Timeout: cfg.Timeout}
if t := interfaceTransport(cfg.Interface); t != nil {
httpClient.Transport = t
}
return &Client{
httpClient: httpClient,
config: cfg,
}
}
func (c *Client) get(url string, target interface{}) error {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return err
}
req.Header.Set("User-Agent", c.config.UserAgent)
req.Header.Set("Accept", "application/json")
resp, err := c.httpClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("bad status: %s, body: %s", resp.Status, string(body))
}
return json.NewDecoder(resp.Body).Decode(target)
}