forked from owenthereal/gh
-
Notifications
You must be signed in to change notification settings - Fork 0
/
request.go
102 lines (83 loc) · 2.03 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
95
96
97
98
99
100
101
102
package sawyer
import (
"github.com/lostisland/go-sawyer/mediaheader"
"github.com/lostisland/go-sawyer/mediatype"
"io/ioutil"
"net/http"
"net/url"
)
type Request struct {
Client *http.Client
MediaType *mediatype.MediaType
Query url.Values
*http.Request
}
func (c *Client) NewRequest(rawurl string) (*Request, error) {
u, err := c.ResolveReferenceString(rawurl)
if err != nil {
return nil, err
}
httpreq, err := http.NewRequest(GetMethod, u, nil)
for key, _ := range c.Header {
httpreq.Header.Set(key, c.Header.Get(key))
}
return &Request{c.HttpClient, nil, httpreq.URL.Query(), httpreq}, err
}
func (r *Request) Do(method string) *Response {
r.URL.RawQuery = r.Query.Encode()
r.Method = method
httpres, err := r.Client.Do(r.Request)
if err != nil {
return ResponseError(err)
}
mtype, err := mediaType(httpres)
if err != nil {
httpres.Body.Close()
return ResponseError(err)
}
headerDecoder := mediaheader.Decoder{}
mheader := headerDecoder.Decode(httpres.Header)
return &Response{nil, mtype, mheader, UseApiError(httpres.StatusCode), false, httpres}
}
func (r *Request) Head() *Response {
return r.Do(HeadMethod)
}
func (r *Request) Get() *Response {
return r.Do(GetMethod)
}
func (r *Request) Post() *Response {
return r.Do(PostMethod)
}
func (r *Request) Put() *Response {
return r.Do(PutMethod)
}
func (r *Request) Patch() *Response {
return r.Do(PatchMethod)
}
func (r *Request) Delete() *Response {
return r.Do(DeleteMethod)
}
func (r *Request) Options() *Response {
return r.Do(OptionsMethod)
}
func (r *Request) SetBody(mtype *mediatype.MediaType, input interface{}) error {
r.MediaType = mtype
buf, err := mtype.Encode(input)
if err != nil {
return err
}
r.Header.Set(ctypeHeader, mtype.String())
r.ContentLength = int64(buf.Len())
r.Body = ioutil.NopCloser(buf)
return nil
}
const (
ctypeHeader = "Content-Type"
HeadMethod = "HEAD"
GetMethod = "GET"
PostMethod = "POST"
PutMethod = "PUT"
PatchMethod = "PATCH"
DeleteMethod = "DELETE"
OptionsMethod = "OPTIONS"
)