-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrequest.go
94 lines (84 loc) · 2.31 KB
/
request.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
// Copyright 2012-present Oliver Eilhard. All rights reserved.
// Use of this source code is governed by a MIT-license.
// See http://olivere.mit-license.org/license.txt for details.
package dorisloader
import (
"bytes"
"compress/gzip"
"encoding/json"
"io"
"net/http"
"runtime"
"strings"
)
type Request http.Request
// NewRequest is a http.Request and adds features such as encoding the body.
func NewRequest(method, url string, body io.Reader) (*Request, error) {
req, err := http.NewRequest(method, url, body)
if err != nil {
return nil, err
}
req.Header.Add("User-Agent", "DorisLoader/"+Version+" ("+runtime.GOOS+"-"+runtime.GOARCH+")")
return (*Request)(req), nil
}
func (r *Request) SetBasicAuth(username, password string) {
((*http.Request)(r)).SetBasicAuth(username, password)
}
func handleGetBodyReader(header http.Header, body interface{}, gzipCompress bool) (io.Reader, error) {
switch b := body.(type) {
case string:
if gzipCompress {
return getBodyGzipReader(header, b)
}
return getBodyString(b)
default:
if gzipCompress {
return getBodyGzipReader(header, body)
}
return getBodyJsonReader(header, body)
}
}
func getBodyJsonReader(header http.Header, data interface{}) (io.Reader, error) {
body, err := json.Marshal(data)
if err != nil {
return nil, err
}
header.Set("Content-Type", "application/json")
return bytes.NewReader(body), nil
}
func getBodyString(body string) (io.Reader, error) {
return strings.NewReader(body), nil
}
func getBodyGzipReader(header http.Header, body interface{}) (io.Reader, error) {
switch b := body.(type) {
case string:
buf := new(bytes.Buffer)
w := gzip.NewWriter(buf)
if _, err := w.Write([]byte(b)); err != nil {
return nil, err
}
if err := w.Close(); err != nil {
return nil, err
}
header.Add("Content-Encoding", "gzip")
header.Add("Vary", "Accept-Encoding")
return bytes.NewReader(buf.Bytes()), nil
default:
data, err := json.Marshal(b)
if err != nil {
return nil, err
}
buf := new(bytes.Buffer)
w := gzip.NewWriter(buf)
if _, err := w.Write(data); err != nil {
return nil, err
}
if err := w.Close(); err != nil {
return nil, err
}
header.Add("Content-Encoding", "gzip")
header.Add("Vary", "Accept-Encoding")
header.Set("Content-Type", "application/json")
return bytes.NewReader(buf.Bytes()), nil
}
}