-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
82 lines (65 loc) · 1.54 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
package monobank
// TODO: add HTTP retry
import (
"errors"
"fmt"
"net/http"
"net/url"
"github.com/vtopc/go-rest"
"github.com/vtopc/go-rest/defaults"
"github.com/vtopc/go-rest/interceptors"
)
const (
baseURL = "https://api.monobank.ua"
)
var ErrEmptyRequest = errors.New("empty request")
type Client struct {
restClient *rest.Client
auth Authorizer
baseURL string // TODO: switch to url.URL
}
// TODO: add WithOpts
// NewClient - returns public monobank Client
func NewClient(client *http.Client) Client {
if client == nil {
client = defaults.NewHTTPClient()
}
_ = interceptors.SetReqContentType(client, "application/json")
c := rest.NewClient(client)
return Client{
restClient: c,
auth: NewPublicAuthorizer(),
baseURL: baseURL,
}
}
// WithBaseURL updates baseURL
func (c *Client) WithBaseURL(uri string) {
c.baseURL = uri
}
func (c *Client) withAuth(auth Authorizer) {
c.auth = auth
}
// do does request.
// Stores JSON response in the value pointed to by v.
// TODO: make expectedStatusCode a slice:
func (c Client) do(req *http.Request, v interface{}, expectedStatusCode int) error {
if req == nil {
return ErrEmptyRequest
}
var err error
req.URL, err = url.Parse(c.baseURL + req.URL.String())
if err != nil {
return fmt.Errorf("failed to build URL: %w", err)
}
if c.auth != nil { // TODO: return an error if not
err = c.auth.SetAuth(req)
if err != nil {
return fmt.Errorf("SetAuth: %w", err)
}
}
err = c.restClient.Do(req, v, expectedStatusCode)
if err != nil {
return err
}
return nil
}