-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
182 lines (146 loc) · 4.45 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
174
175
176
177
178
179
180
181
182
package ltt
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/http/cookiejar"
"net/url"
"strings"
"time"
)
type httpClientContextKeyType int
var httpClientContextKey httpClientContextKeyType
func NewHTTPClient(ctx context.Context, baseURI string) *HTTPClient {
jar, err := cookiejar.New(&cookiejar.Options{})
if err != nil {
log.Fatalf("failed to create cookie jar: %w", err)
}
lt := FromContext(ctx)
std_client := &http.Client{
Timeout: time.Second * time.Duration(lt.Config.RequestTimeout),
Jar: jar,
}
client := &HTTPClient{
std: std_client,
baseURI: baseURI,
user: UserFromContext(ctx),
Headers: make(http.Header),
ErrorOnErrorCode: true,
}
return client
}
func NewHTTPClientContext(ctx context.Context, client *HTTPClient) context.Context {
return context.WithValue(ctx, httpClientContextKey, client)
}
func HTTPClientFromContext(ctx context.Context) *HTTPClient {
if c, ok := ctx.Value(httpClientContextKey).(*HTTPClient); ok {
return c
}
return nil
}
type HTTPClient struct {
std *http.Client
// Base uri to append the path to, e.g. "http://localhost/"
baseURI string
// The owning User of this http client
user User
// These headers will be set in all requests
Headers http.Header
// If true, 4xx-5xx status code will return an error, defaults to true
ErrorOnErrorCode bool
}
type HTTPResponse struct {
StatusCode int
Body []byte
RawResponse *http.Response
}
func (resp *HTTPResponse) JSON(out interface{}) error {
return json.Unmarshal(resp.Body, out)
}
func (c *HTTPClient) getUrl(path string) string {
return fmt.Sprint(strings.TrimRight(c.baseURI, "/"), path)
}
func (c *HTTPClient) handleResponse(method string, path string, std_resp *http.Response) (*HTTPResponse, error) {
response_body, err := ioutil.ReadAll(std_resp.Body)
if err != nil {
return nil, err
}
if std_resp.StatusCode >= http.StatusBadRequest {
return nil, fmt.Errorf("error status code %d: %s", std_resp.StatusCode, string(response_body))
}
resp := &HTTPResponse{
StatusCode: std_resp.StatusCode,
Body: response_body,
RawResponse: std_resp,
}
lt := FromContext(c.user.Context())
if lt.Config.Verbose {
lt.Log.Printf("HTTPClient(user %d): response for %s %s: %d (%d bytes)\n",
c.user.ID(), method, path, resp.StatusCode, len(resp.Body))
}
return resp, nil
}
func (c *HTTPClient) Request(method string, path string, body []byte) (*HTTPResponse, error) {
lt := FromContext(c.user.Context())
if FromContext(c.user.Context()).Config.Verbose {
lt.Log.Printf("HTTPClient(user %d): requesting %s %s\n", c.user.ID(), method, path)
}
std_req, err := http.NewRequest(method, c.getUrl(path), bytes.NewReader(body))
if err != nil {
return nil, err
}
// Set the default headers
for k, v := range c.Headers {
std_req.Header[k] = v
}
std_resp, err := c.std.Do(std_req)
if err != nil {
return nil, err
}
return c.handleResponse(method, path, std_resp)
}
func (c *HTTPClient) Get(path string) (*HTTPResponse, error) {
return c.Request(http.MethodGet, path, nil)
}
func (c *HTTPClient) Options(path string) (*HTTPResponse, error) {
return c.Request(http.MethodOptions, path, nil)
}
func (c *HTTPClient) Head(path string) (*HTTPResponse, error) {
return c.Request(http.MethodHead, path, nil)
}
func (c *HTTPClient) Delete(path string) (*HTTPResponse, error) {
return c.Request(http.MethodDelete, path, nil)
}
func (c *HTTPClient) Post(path string, body []byte) (*HTTPResponse, error) {
return c.Request(http.MethodPost, path, body)
}
func (c *HTTPClient) PostForm(path string, data url.Values) (*HTTPResponse, error) {
lt := FromContext(c.user.Context())
if lt.Config.Verbose {
lt.Log.Printf("HTTPClient(user %d): requesting %s %s\n", c.user.ID(), http.MethodPost, path)
}
std_req, err := http.NewRequest(http.MethodPost, c.getUrl(path), strings.NewReader(data.Encode()))
if err != nil {
return nil, err
}
// Set the default headers
for k, v := range c.Headers {
std_req.Header[k] = v
}
std_req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
std_resp, err := c.std.Do(std_req)
if err != nil {
return nil, err
}
return c.handleResponse(http.MethodPost, path, std_resp)
}
func (c *HTTPClient) Patch(path string, body []byte) (*HTTPResponse, error) {
return c.Request(http.MethodPatch, path, body)
}
func (c *HTTPClient) Put(path string, body []byte) (*HTTPResponse, error) {
return c.Request(http.MethodPut, path, body)
}