-
Notifications
You must be signed in to change notification settings - Fork 15
/
client.go
75 lines (63 loc) · 1.39 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
package widevine
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
"time"
)
// HTTPClient defines an HTTP client.
type HTTPClient struct {
*http.Client
}
func (c *HTTPClient) get(url string, i interface{}) error {
rsp, e := c.Get(url)
if e != nil {
return e
}
defer rsp.Body.Close()
b, e := ioutil.ReadAll(rsp.Body)
if e != nil {
return e
}
if rsp.Status[0] != '2' {
return fmt.Errorf("expected status 2xx, got %s: %s", rsp.Status, string(b))
}
return json.Unmarshal(b, &i)
}
func (c *HTTPClient) post(url string, i interface{}, body interface{}) error {
payload, _ := json.Marshal(body)
req, e := http.NewRequest("POST", url, bytes.NewBuffer(payload))
if e != nil {
return e
}
req.Header.Add("content-type", "application/json")
rsp, e := http.DefaultClient.Do(req)
if e != nil {
return e
}
defer rsp.Body.Close()
b, e := ioutil.ReadAll(rsp.Body)
if e != nil {
return e
}
if rsp.Status[0] != '2' {
return fmt.Errorf("expected status 2xx, got %s: %s", rsp.Status, string(b))
}
return json.Unmarshal(b, &i)
}
// NewClient creates an HTTPClient instance.
func NewClient() (*HTTPClient, error) {
var netTransport = &http.Transport{
Dial: (&net.Dialer{
Timeout: 5 * time.Second,
}).Dial,
TLSHandshakeTimeout: 5 * time.Second,
}
return &HTTPClient{Client: &http.Client{
Timeout: time.Second * 10,
Transport: netTransport,
}}, nil
}