-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp_client.go
55 lines (45 loc) · 1.04 KB
/
http_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
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"time"
)
type Services []string
var services = Services{
"https://ipapi.co/json",
"http://ip-api.com/json",
"https://freegeoip.app/json/",
"http://worldtimeapi.org/api/ip",
}
type Client struct {
client *http.Client
}
type response struct {
Timezone string `json:"timezone"`
}
func (c *Client) GetTimezone(ctx context.Context, url string) (*response, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, fmt.Errorf("could not create a new request: %w", err)
}
res, err := c.client.Do(req)
if err != nil {
return nil, fmt.Errorf("request failed: %w", err)
}
defer res.Body.Close()
response := new(response)
if err := json.NewDecoder(res.Body).Decode(response); err != nil {
return nil, fmt.Errorf("unable to decode JSON response: %w", err)
}
return response, nil
}
func NewClient() *Client {
return &Client{
client: &http.Client{
Timeout: 30 * time.Second,
Transport: http.DefaultTransport,
},
}
}