-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathhttp.go
241 lines (219 loc) · 8.91 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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
// Copyright (c) 2020 Xelaj Software
//
// This file is a part of go-dry package.
// See https://github.com/xelaj/go-dry/blob/master/LICENSE for details
package dry
import (
"bytes"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"strings"
)
type wrappedResponseWriter struct {
io.Writer
http.ResponseWriter
}
func (wrapped wrappedResponseWriter) Write(data []byte) (int, error) {
return wrapped.Writer.Write(data)
}
// HTTPCompressHandlerFunc wraps a http.HandlerFunc so that the response gets
// gzip or deflate compressed if the Accept-Encoding header of the request allows it.
func HTTPCompressHandlerFunc(handlerFunc http.HandlerFunc) http.HandlerFunc {
return func(response http.ResponseWriter, request *http.Request) {
NewHTTPCompressHandlerFromFunc(handlerFunc).ServeHTTP(response, request)
}
}
// HTTPCompressHandler wraps a http.Handler so that the response gets
// gzip or deflate compressed if the Accept-Encoding header of the request allows it.
type HTTPCompressHandler struct {
http.Handler
}
func NewHTTPCompressHandler(handler http.Handler) *HTTPCompressHandler {
return &HTTPCompressHandler{handler}
}
func NewHTTPCompressHandlerFromFunc(handler http.HandlerFunc) *HTTPCompressHandler {
return &HTTPCompressHandler{handler}
}
func (h *HTTPCompressHandler) ServeHTTP(response http.ResponseWriter, request *http.Request) {
accept := request.Header.Get("Accept-Encoding")
if strings.Contains(accept, "gzip") {
response.Header().Set("Content-Encoding", "gzip")
writer := Gzip.GetWriter(response)
defer Gzip.ReturnWriter(writer)
response = wrappedResponseWriter{Writer: writer, ResponseWriter: response}
} else if strings.Contains(accept, "deflate") {
response.Header().Set("Content-Encoding", "deflate")
writer := Deflate.GetWriter(response)
defer Deflate.ReturnWriter(writer)
response = wrappedResponseWriter{Writer: writer, ResponseWriter: response}
}
h.Handler.ServeHTTP(response, request)
}
// HTTPPostJSON marshalles data as JSON
// and sends it as HTTP POST request to url.
// If the response status code is not 200 OK,
// then the status is returned as an error.
func HTTPPostJSON(url string, data any) error {
b, err := json.MarshalIndent(data, "", " ")
if err != nil {
return err
}
req := &http.Request{
Method: http.MethodPost,
Body: ioutil.NopCloser(bytes.NewReader(b)),
}
req.Header.Set("Content-Type", "application/json")
response, err := http.DefaultClient.Do(req)
defer response.Body.Close()
if err == nil && (response.StatusCode < 200 || response.StatusCode > 299) {
err = errors.New(response.Status)
}
return err
}
// HTTPPostXML marshalles data as XML
// and sends it as HTTP POST request to url.
// If the response status code is not 200 OK,
// then the status is returned as an error.
func HTTPPostXML(url string, data any) error {
b, err := xml.MarshalIndent(data, "", " ")
if err != nil {
return err
}
req := &http.Request{
Method: http.MethodPost,
Body: ioutil.NopCloser(bytes.NewReader(b)),
}
req.Header.Set("Content-Type", "application/xml")
response, err := http.DefaultClient.Do(req)
if err == nil && (response.StatusCode < 200 || response.StatusCode > 299) {
err = errors.New(response.Status)
}
_ = response.Body.Close()
return err
}
// HTTPDelete performs a HTTP DELETE request
func HTTPDelete(url string) (statusCode int, statusText string, err error) {
request, err := http.NewRequest("DELETE", url, nil)
if err != nil {
return 0, "", err
}
response, err := http.DefaultClient.Do(request)
if err != nil {
return 0, "", err
}
return response.StatusCode, response.Status, response.Body.Close()
}
// HTTPPostForm performs a HTTP POST request with data as application/x-www-form-urlencoded
func HTTPPostForm(url string, data url.Values) (statusCode int, statusText string, err error) {
request, err := http.NewRequest("POST", url, strings.NewReader(data.Encode()))
if err != nil {
return 0, "", err
}
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
response, err := http.DefaultClient.Do(request)
if err != nil {
return 0, "", err
}
return response.StatusCode, response.Status, response.Body.Close()
}
// HTTPPutForm performs a HTTP PUT request with data as application/x-www-form-urlencoded
func HTTPPutForm(url string, data url.Values) (statusCode int, statusText string, err error) {
request, err := http.NewRequest("PUT", url, strings.NewReader(data.Encode()))
if err != nil {
return 0, "", err
}
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
response, err := http.DefaultClient.Do(request)
if err != nil {
return 0, "", err
}
return response.StatusCode, response.Status, response.Body.Close()
}
// HTTPRespondMarshalJSON marshals response as JSON to responseWriter, sets Content-Type to application/json
// and compresses the response if Content-Encoding from the request allows it.
func HTTPRespondMarshalJSON(response any, responseWriter http.ResponseWriter, request *http.Request) (err error) {
NewHTTPCompressHandlerFromFunc(func(responseWriter http.ResponseWriter, request *http.Request) {
var data []byte
if data, err = json.Marshal(response); err == nil {
responseWriter.Header().Set("Content-Type", "application/json")
_, err = responseWriter.Write(data)
}
}).ServeHTTP(responseWriter, request)
return err
}
// HTTPRespondMarshalIndentJSON marshals response as JSON to responseWriter, sets Content-Type to application/json
// and compresses the response if Content-Encoding from the request allows it.
// The JSON will be marshalled indented according to json.MarshalIndent
func HTTPRespondMarshalIndentJSON(response any, prefix, indent string, responseWriter http.ResponseWriter, request *http.Request) (err error) {
NewHTTPCompressHandlerFromFunc(func(responseWriter http.ResponseWriter, request *http.Request) {
var data []byte
if data, err = json.MarshalIndent(response, prefix, indent); err == nil {
responseWriter.Header().Set("Content-Type", "application/json")
_, err = responseWriter.Write(data)
}
}).ServeHTTP(responseWriter, request)
return err
}
// HTTPRespondMarshalXML marshals response as XML to responseWriter, sets Content-Type to application/xml
// and compresses the response if Content-Encoding from the request allows it.
// If rootElement is not empty, then an additional root element with this name will be wrapped around the content.
func HTTPRespondMarshalXML(response any, rootElement string, responseWriter http.ResponseWriter, request *http.Request) (err error) {
NewHTTPCompressHandlerFromFunc(func(responseWriter http.ResponseWriter, request *http.Request) {
var data []byte
if data, err = xml.Marshal(response); err == nil {
responseWriter.Header().Set("Content-Type", "application/xml")
if rootElement == "" {
_, err = fmt.Fprintf(responseWriter, "%s%s", xml.Header, data)
} else {
_, err = fmt.Fprintf(responseWriter, "%s<%s>%s</%s>", xml.Header, rootElement, data, rootElement)
}
}
}).ServeHTTP(responseWriter, request)
return err
}
// HTTPRespondMarshalIndentXML marshals response as XML to responseWriter, sets Content-Type to application/xml
// and compresses the response if Content-Encoding from the request allows it.
// The XML will be marshalled indented according to xml.MarshalIndent.
// If rootElement is not empty, then an additional root element with this name will be wrapped around the content.
func HTTPRespondMarshalIndentXML(response any, rootElement string, prefix, indent string, responseWriter http.ResponseWriter, request *http.Request) (err error) {
NewHTTPCompressHandlerFromFunc(func(responseWriter http.ResponseWriter, request *http.Request) {
var data []byte
contentPrefix := prefix
if rootElement != "" {
contentPrefix += indent
}
if data, err = xml.MarshalIndent(response, contentPrefix, indent); err == nil {
responseWriter.Header().Set("Content-Type", "application/xml")
if rootElement == "" {
_, err = fmt.Fprintf(responseWriter, "%s%s\n%s", prefix, xml.Header, data)
} else {
_, err = fmt.Fprintf(responseWriter, "%s%s%s<%s>\n%s\n%s</%s>", prefix, xml.Header, prefix, rootElement, data, prefix, rootElement)
}
}
}).ServeHTTP(responseWriter, request)
return err
}
// HTTPRespondText sets Content-Type to text/plain
// and compresses the response if Content-Encoding from the request allows it.
func HTTPRespondText(response string, responseWriter http.ResponseWriter, request *http.Request) (err error) {
NewHTTPCompressHandlerFromFunc(func(responseWriter http.ResponseWriter, request *http.Request) {
responseWriter.Header().Set("Content-Type", "text/plain")
_, err = responseWriter.Write([]byte(response))
}).ServeHTTP(responseWriter, request)
return err
}
// HTTPUnmarshalRequestBodyJSON reads a http.Request body and unmarshals it as JSON to result.
func HTTPUnmarshalRequestBodyJSON(request *http.Request, result any) error {
defer request.Body.Close()
body, err := ioutil.ReadAll(request.Body)
if err != nil {
return err
}
return json.Unmarshal(body, result)
}