-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathhttp.go
173 lines (145 loc) · 3.66 KB
/
http.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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
package http
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
)
// https://ethereum.github.io/beacon-APIs/#/
type Config struct {
logger *log.Logger
untrackedKeys bool
}
type ConfigOption func(*Config)
func WithLogger(logger *log.Logger) ConfigOption {
return func(c *Config) {
c.logger = logger
}
}
func WithUntrackedKeys() ConfigOption {
return func(c *Config) {
c.untrackedKeys = true
}
}
type Client struct {
url string
config *Config
}
func New(url string, opts ...ConfigOption) *Client {
config := &Config{
logger: log.New(io.Discard, "", 0),
}
for _, opt := range opts {
opt(config)
}
return &Client{url: url, config: config}
}
func (c *Client) SetLogger(logger *log.Logger) {
c.config.logger = logger
}
func (c *Client) Post(path string, input interface{}, out interface{}) error {
postBody, err := Marshal(input)
if err != nil {
return err
}
responseBody := bytes.NewBuffer(postBody)
resp, err := http.Post(c.url+path, "application/json", responseBody)
if err != nil {
return err
}
defer resp.Body.Close()
if err := c.decodeResp(resp, out); err != nil {
return err
}
return nil
}
func (c *Client) Status(path string) (bool, error) {
resp, err := http.Get(c.url + path)
if err != nil {
return false, err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
return true, nil
}
errorMsg, ok := httpErrorMapping[resp.StatusCode]
if ok {
return false, errorMsg
}
return false, fmt.Errorf("status code != 200: %d", resp.StatusCode)
}
func (c *Client) Get(path string, out interface{}) error {
resp, err := http.Get(c.url + path)
if err != nil {
return err
}
defer resp.Body.Close()
c.config.logger.Printf("[TRACE] Get request: path, %s", path)
if err := c.decodeResp(resp, out); err != nil {
return err
}
return nil
}
var (
ErrorIncompleteData = fmt.Errorf("incomplete data (206)")
ErrorBadRequest = fmt.Errorf("bad request (400)")
ErrorNotFound = fmt.Errorf("not found (404)")
ErrorInternalServerError = fmt.Errorf("internal server error (500)")
ErrorServiceUnavailable = fmt.Errorf("service unavailable (503)")
)
var httpErrorMapping = map[int]error{
http.StatusPartialContent: ErrorIncompleteData,
http.StatusBadRequest: ErrorBadRequest,
http.StatusNotFound: ErrorNotFound,
http.StatusInternalServerError: ErrorInternalServerError,
http.StatusServiceUnavailable: ErrorServiceUnavailable,
}
type httpErrorMessage struct {
Code uint64 `json:"code"`
Message string `json:"message"`
}
func (c *Client) decodeResp(resp *http.Response, out interface{}) error {
data, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
// decode the error message
var msg httpErrorMessage
if err := json.Unmarshal(data, &msg); err != nil {
return err
}
errorMsgCode, ok := httpErrorMapping[resp.StatusCode]
if ok {
return fmt.Errorf("%w: %v", errorMsgCode, msg.Message)
}
// return the error message as is
return fmt.Errorf(msg.Message)
}
c.config.logger.Printf("[TRACE] Http response: data, %s", string(data))
if resp.Request.Method == http.MethodPost && out == nil {
// post methods that expects no output
if string(data) == `{"data":null}` {
return nil
}
if string(data) == "null" {
return nil
}
if string(data) == "" {
return nil
}
return fmt.Errorf("json failed to decode post message: '%s'", string(data))
}
var output struct {
Data json.RawMessage `json:"data,omitempty"`
}
if err := json.Unmarshal(data, &output); err != nil {
return err
}
if err := Unmarshal(output.Data, &out, c.config.untrackedKeys); err != nil {
return err
}
return nil
}