-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjson.go
62 lines (51 loc) · 1.15 KB
/
json.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 easyreq
import (
"bytes"
"encoding/json"
"net/http"
)
type Json struct {
payload interface{}
header http.Header
}
func NewJson(payload interface{}) *Json {
j := &Json{}
j.payload = payload
return j
}
func (j *Json) Set(payload interface{}) *Json {
j.payload = payload
return j
}
func (j *Json) Header() http.Header {
if j.header == nil {
j.header = make(http.Header)
}
return j.header
}
// Helper funcation send requests using http.DefaultClient
func (j *Json) Do(verb, urlStr string) (*http.Response, error) {
return do(j, verb, urlStr)
}
func (j *Json) SetBasicAuth(username, password string) {
setBasicAuth(j, username, password)
}
// Returns request based on current payload assoicated with Json request,
// it will always have correct Content-Type set
func (j *Json) Request(verb, urlStr string) (req *http.Request, err error) {
var data []byte
if j.payload != nil {
data, err = json.Marshal(j.payload)
if err != nil {
return
}
}
body := bytes.NewBuffer(data)
req, err = http.NewRequest(verb, urlStr, body)
if err != nil {
return
}
req.Header = j.Header()
req.Header.Set("Content-Type", "application/json")
return
}