-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhttp.go
98 lines (85 loc) · 2.37 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
package sensonet
// Copied from https://github.com/evcc-io/evcc
import (
"encoding/json"
"fmt"
"io"
"net/http"
)
var (
JSONContent = "application/json"
// JSONEncoding specifies application/json
JSONEncoding = map[string]string{
"Content-Type": JSONContent,
"Accept": JSONContent,
}
// AcceptJSON accepting application/json
AcceptJSON = map[string]string{
"Accept": JSONContent,
}
)
// Helper provides utility primitives
type Helper struct {
*http.Client
}
// doBody executes HTTP request and returns the response body
func doBody(r *http.Client, req *http.Request) ([]byte, error) {
resp, err := r.Do(req)
var body []byte
if err == nil {
body, err = ReadBody(resp)
}
return body, err
}
// decodeJSON reads HTTP response and decodes JSON body if error is nil
func decodeJSON(resp *http.Response, res interface{}) error {
if err := ResponseError(resp); err != nil {
_ = json.NewDecoder(resp.Body).Decode(&res)
return err
}
return json.NewDecoder(resp.Body).Decode(&res)
}
// doJSON executes HTTP request and decodes JSON response.
// It returns a StatusError on response codes other than HTTP 2xx.
func doJSON(r *http.Client, req *http.Request, res interface{}) error {
resp, err := r.Do(req)
if err == nil {
defer resp.Body.Close()
err = decodeJSON(resp, &res)
}
return err
}
// StatusError indicates unsuccessful http response
type StatusError struct {
resp *http.Response
}
func (e StatusError) Error() string {
return fmt.Sprintf("unexpected status: %d (%s)", e.resp.StatusCode, http.StatusText(e.resp.StatusCode))
}
// Response returns the response with the unexpected error
func (e StatusError) Response() *http.Response {
return e.resp
}
// StatusCode returns the response's status code
func (e StatusError) StatusCode() int {
return e.resp.StatusCode
}
// ResponseError turns an HTTP status code into an error
func ResponseError(resp *http.Response) error {
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return StatusError{resp: resp}
}
return nil
}
// ReadBody reads HTTP response and returns error on response codes other than HTTP 2xx. It closes the request body after reading.
func ReadBody(resp *http.Response) ([]byte, error) {
defer resp.Body.Close()
b, err := io.ReadAll(resp.Body)
if err != nil {
return []byte{}, err
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return b, StatusError{resp: resp}
}
return b, nil
}