-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathprovider.go
106 lines (87 loc) · 2.36 KB
/
provider.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
package sdk
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
)
var _ Provider = &defaultHTTP{}
type (
// Provider interface for change provider client.
Provider interface {
Get(ctx context.Context, url string, token string, unmarshal interface{}) error
Post(ctx context.Context, url string, token string, payload, unmarshal interface{}) error
}
defaultHTTP struct {
client *http.Client
}
)
// Post for implements Provider.
func (c *defaultHTTP) Post(ctx context.Context, url string, token string, payload, unmarshal interface{}) error {
var body io.ReadWriter
if payload != nil {
buf, err := json.Marshal(payload)
if err != nil {
return fmt.Errorf("json marslal: %w", err)
}
body = bytes.NewBuffer(buf)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, body)
if err != nil {
return fmt.Errorf("build new request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+token)
resp, err := c.do(req)
if err != nil {
return fmt.Errorf("provider do: %w", err)
}
defer resp.Body.Close()
if unmarshal != nil {
err = json.NewDecoder(resp.Body).Decode(unmarshal)
if err != nil {
return fmt.Errorf("decode json: %w", err)
}
}
return nil
}
// Get for implements Provider.
func (c *defaultHTTP) Get(ctx context.Context, url string, token string, unmarshal interface{}) error {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return fmt.Errorf("build new request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+token)
resp, err := c.do(req)
if err != nil {
return fmt.Errorf("provider do: %w", err)
}
defer resp.Body.Close()
err = json.NewDecoder(resp.Body).Decode(unmarshal)
if err != nil {
return fmt.Errorf("decode json: %w", err)
}
return nil
}
func (c *defaultHTTP) do(req *http.Request) (*http.Response, error) {
resp, err := c.client.Do(req)
if err != nil {
return nil, fmt.Errorf("provider client do: %w", err)
}
switch resp.StatusCode {
case http.StatusOK:
case http.StatusNotFound:
return nil, ErrNotFound
default:
tradingError := TradingError{}
err := json.NewDecoder(resp.Body).Decode(&tradingError)
if err != nil {
return nil, fmt.Errorf("json decode error: %w", err)
}
return nil, tradingError
}
return resp, nil
}