-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
103 lines (84 loc) · 2.23 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package ifunny
import (
"encoding/json"
"fmt"
"io"
"net/http"
"github.com/google/uuid"
"github.com/open-ifunny/discovery-bot/ifunny/compose"
"github.com/sirupsen/logrus"
)
const (
apiRoot = "https://api.ifunny.mobi/v4"
projectID = "iFunny"
LogLevel = logrus.InfoLevel
)
func MakeClient(bearer, userAgent string) (*Client, error) {
client := &Client{bearer, userAgent, http.DefaultClient, logrus.New(), nil}
client.log.SetFormatter(&logrus.JSONFormatter{})
client.log.SetLevel(LogLevel)
self, err := client.GetUser(compose.UserAccount())
if err != nil {
return nil, err
}
client.Self = self
return client, nil
}
func MakeClientLog(bearer, userAgent string, log *logrus.Logger) (*Client, error) {
client, err := MakeClient(bearer, userAgent)
if err != nil {
return nil, err
}
client.log = log
return client, nil
}
type Client struct {
bearer, userAgeng string
http *http.Client
log *logrus.Logger
Self *User
}
func request(desc compose.Request, header http.Header, client *http.Client) (*http.Response, error) {
request, err := http.NewRequest(desc.Method, apiRoot+desc.Path, desc.Body)
if err != nil {
return nil, err
}
request.Header = header
request.URL.RawQuery = desc.Query.Encode()
return client.Do(request)
}
func (client *Client) header() http.Header {
return http.Header{
"authorization": []string{"bearer " + client.bearer},
"user-agent": []string{client.userAgeng},
"ifunny-project-id": []string{projectID},
}
}
func (client *Client) RequestJSON(desc compose.Request, output interface{}) error {
traceID := uuid.New().String()
log := client.log.WithFields(logrus.Fields{
"trace_id": traceID,
"path": desc.Path,
"method": desc.Method,
"query": desc.Query.Encode(),
"has_body": desc.Body != nil},
)
log.Trace("make request")
response, err := request(desc, client.header(), client.http)
if err != nil {
log.Error(err)
return err
}
log.Trace(fmt.Sprintf("got response %s", response.Status))
bodyBytes, err := io.ReadAll(response.Body)
if err != nil {
log.Error(err)
return err
}
log.Trace(fmt.Sprintf("got response body %s", string(bodyBytes)))
err = json.Unmarshal(bodyBytes, output)
if err != nil {
log.Error(err)
}
return err
}