-
Notifications
You must be signed in to change notification settings - Fork 12
/
client.go
153 lines (125 loc) · 3.44 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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
package misskey
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
"github.com/sirupsen/logrus"
"github.com/yitsushi/go-misskey/core"
"golang.org/x/net/context"
)
// Client is the main Misskey client struct.
type Client struct {
BaseURL string
Token string
HTTPClient core.HTTPClient
logger *logrus.Logger
}
// RequestTimout is the timeout of a request in seconds.
const RequestTimout = 10
// NewClient creates a new Misskey Client.
//
// Deprecated: use NewClientWithOptions instead.
func NewClient(baseURL, token string) *Client {
return &Client{
Token: token,
BaseURL: baseURL,
HTTPClient: &http.Client{
Timeout: time.Second * RequestTimout,
},
logger: logrus.New(),
}
}
// NewClientWithOptions creates a new Misskey Client with defined options.
func NewClientWithOptions(options ...ClientOption) (*Client, error) {
client := &Client{
Token: "",
BaseURL: "",
HTTPClient: nil,
logger: logrus.New(),
}
for _, opt := range options {
err := opt(client)
if err != nil {
return nil, err
}
}
if client.HTTPClient == nil {
client.HTTPClient = &http.Client{
Timeout: time.Second * RequestTimout,
}
}
return client, nil
}
// LogLevel sets logger level.
func (c *Client) LogLevel(level logrus.Level) {
c.logger.SetLevel(level)
}
func (c Client) url(path string) string {
return fmt.Sprintf("%s/api%s", c.BaseURL, path)
}
func (c Client) sendRequest(request core.Request, response interface{}) error {
requestBody, contentType, err := request.ToBody(c.Token)
if err != nil {
return err
}
req, err := http.NewRequestWithContext(
context.Background(),
http.MethodPost,
c.url(request.EndpointPath()),
bytes.NewBuffer(requestBody),
)
if err != nil {
return fmt.Errorf("unable to create new request: %w", err)
}
req.Header.Set("Content-Type", contentType)
req.Header.Set("User-Agent", "Misskey Go SDK")
c.logger.WithField("_type", "request").Debugf("%s %s", req.Method, req.URL)
c.logger.WithField("_type", "request").Debugf("%s", requestBody)
resp, err := c.HTTPClient.Do(req)
if err != nil {
return core.RequestError{Message: core.ResponseReadError, Origin: err}
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return core.RequestError{Message: core.ResponseReadBodyError, Origin: err}
}
c.logger.WithFields(logrus.Fields{
"_type": "response",
"from": req.URL,
"code": resp.StatusCode,
}).Debugf("%s", body)
if resp.StatusCode == http.StatusOK {
if err := json.Unmarshal(body, response); err != nil {
return fmt.Errorf("unable to parse response: %w", err)
}
return nil
}
if resp.StatusCode == http.StatusNoContent {
// Status code 204 considered as valid status code
// if given operation was processed, no error occurred
// but nothing to return, like delete resources.
return nil
}
if resp.StatusCode == http.StatusNotFound {
return core.EndpointNotFoundError{
Endpoint: request.EndpointPath(),
}
}
return unwrapError(body)
}
func unwrapError(body []byte) error {
var errorWrapper core.ErrorResponseWrapperError
err := json.Unmarshal(body, &errorWrapper)
if err != nil {
return core.RequestError{Message: core.ErrorResponseParseError, Origin: err}
}
var errorResponse core.ErrorResponse
if err := json.Unmarshal(errorWrapper.Error, &errorResponse); err != nil {
return core.RequestError{Message: core.ErrorResponseParseError, Origin: err}
}
return core.UnknownError{Response: errorResponse}
}