/
restclient.go
executable file
·53 lines (44 loc) · 1.11 KB
/
restclient.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
package httpclient
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"github.com/HHHHHHRen/httpclient/mimetype"
"io"
"io/ioutil"
"net/http"
)
// UnmarshalJson executes the http request client and returns http.Response and error.
func (b *Builder) UnmarshalJson(v interface{}) (*http.Response, error) {
resp, err := b.Do()
if err != nil {
return resp, err
}
body, _ := ioutil.ReadAll(resp.Body)
resp.Body = ioutil.NopCloser(bytes.NewBuffer(body))
if body == nil{
return nil, errors.New(fmt.Sprintf("url : %v ,response body is nil",b.Url))
}
err = json.Unmarshal(body, v)
return resp, err
}
func (b *Builder) newJsonRequest() *http.Request {
var reader io.Reader
if len(b.bodyByte) > 0 {
reader = bytes.NewBuffer(b.bodyByte)
}
req, _ := http.NewRequest(b.Method, b.Url, reader)
//Set Default Content-Type Header
req.Header.Set("Content-Type", mimetype.ApplicationJson)
//Set Header
for k, v := range b.Headers {
req.Header.Set(k, v)
}
//Set Query
req.URL.RawQuery = b.Queries.Encode()
if b.basicAuth != (auth{}) {
req.SetBasicAuth(b.basicAuth.username, b.basicAuth.password)
}
return req
}