-
-
Notifications
You must be signed in to change notification settings - Fork 38
/
httprequest.go
71 lines (59 loc) · 1.83 KB
/
httprequest.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
// Package httpreq provides general utilities for
// around net/http requests for a simpler API and
// extra utilities for parsing JSON request and
// response boddies.
package httpreq
import (
"bytes"
"encoding/json"
"io"
"github.com/valyala/fasthttp"
)
// Request executes a HTTP request with the given method to the
// given URL and attaches the passed headers. When data is passed,
// the object will be serialized using JSON encoder and attached to
// the request body.
func Request(method, url string, headers map[string]string, data interface{}) (res *Response, err error) {
defer func() {
if err != nil && res != nil {
res.Release()
}
}()
req := fasthttp.AcquireRequest()
defer fasthttp.ReleaseRequest(req)
res = responsePool.Get()
req.Header.SetMethod(method)
req.SetRequestURI(url)
for k, v := range headers {
req.Header.Add(k, v)
}
if data != nil {
err = json.NewEncoder(req.BodyWriter()).Encode(data)
if err != nil {
return
}
}
err = fasthttp.Do(req, res.Response)
return
}
// Get is shorthand for Request using the GET method.
func Get(url string, headers map[string]string) (*Response, error) {
return Request("GET", url, headers, nil)
}
// Post is shorthand for Request using the POST method.
func Post(url string, headers map[string]string, data interface{}) (*Response, error) {
return Request("POST", url, headers, data)
}
// GetFile is shorthand for http.Get and returns
// the body as io.Reader as well as occured errors
// during request execution.
func GetFile(url string, headers map[string]string) (r io.Reader, contentType string, err error) {
resp, err := Get(url, headers)
if err != nil {
return
}
defer resp.Release()
r = bytes.NewBuffer(resp.Body())
contentType = string(resp.Header.Peek("content-type"))
return
}