-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
85 lines (69 loc) · 1.6 KB
/
client.go
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
73
74
75
76
77
78
79
80
81
82
83
84
85
package ifconfigme
import (
"encoding/json"
"fmt"
"io"
"net/http"
"time"
)
const ifconfigMeUrl = "https://ifconfig.me/all.json"
type Response struct {
IpAddr string `json:"ip_addr"`
RemoteHost string `json:"remote_host"`
UserAgent string `json:"user_agent"`
Port string `json:"port"`
Language string `json:"language"`
Method string `json:"method"`
Encoding string `json:"encoding"`
Mime string `json:"mime"`
Via string `json:"via"`
Forwarded string `json:"forwarded"`
}
type Client struct {
httpClient *http.Client
}
type ClientOption func(*Client)
func WithTransport(transport *http.Transport) ClientOption {
return func(c *Client) {
c.httpClient.Transport = transport
}
}
func WithTimeout(timeout time.Duration) ClientOption {
return func(c *Client) {
c.httpClient.Timeout = timeout
}
}
func NewClient(opts ...ClientOption) *Client {
timeout := 500 * time.Millisecond
transport := &http.Transport{}
client := &Client{
httpClient: &http.Client{
Transport: transport,
Timeout: timeout,
},
}
for _, opt := range opts {
opt(client)
}
return client
}
func (r *Client) Get() (*Response, error) {
httpResponse, err := r.httpClient.Get(ifconfigMeUrl)
if err != nil {
return nil, err
}
defer httpResponse.Body.Close()
if httpResponse.StatusCode != 200 {
return nil, fmt.Errorf("http status %d", httpResponse.StatusCode)
}
httpBody, err := io.ReadAll(httpResponse.Body)
if err != nil {
return nil, err
}
var response Response
err = json.Unmarshal(httpBody, &response)
if err != nil {
return nil, err
}
return &response, nil
}