-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
62 lines (57 loc) · 1.36 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
package skadigo
import (
"errors"
"fmt"
"io"
"net/http"
)
// RoundTripper for auto add auth header
// Debug mode will mock out request
type roundTripper struct {
debug bool
token string
r http.RoundTripper
}
// RoundTrip RoundTripper interface
func (rt roundTripper) RoundTrip(r *http.Request) (*http.Response, error) {
if rt.debug {
return &http.Response{
Request: r,
StatusCode: http.StatusNoContent,
}, nil
}
r.Header.Add("Authorization", "Bearer "+rt.token)
r.Header.Add("Content-Type", "application/json")
return rt.r.RoundTrip(r)
}
func customRoundTripper(token string, debug bool) http.RoundTripper {
return roundTripper{
debug: debug,
token: token,
r: http.DefaultTransport,
}
}
func (a *Agent) request(r *http.Request) (*http.Response, error) {
resp, err := a.httpc.Do(r)
if err != nil {
return nil, err
}
// success
if resp.StatusCode < 400 {
return resp, nil
}
// failed
if resp.StatusCode == 401 {
return nil, errors.New("invalid token")
}
if resp.StatusCode >= 500 {
return nil, fmt.Errorf("server error,status code: %d", resp.StatusCode)
}
// read error body
body, err := io.ReadAll(resp.Body)
_ = resp.Body.Close()
if err != nil {
return nil, fmt.Errorf("parse http error resp body failed: %w", err)
}
return nil, fmt.Errorf("http request error, status: %d, error: %s", resp.StatusCode, string(body))
}