/
httptest.go
123 lines (98 loc) · 2.51 KB
/
httptest.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
// Copyright 2014 Simon Zimmermann. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package httputil
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"reflect"
"strings"
)
type Request http.Request
type Response http.Response
// NewRequest wraps http.Request
func NewRequest(method string, uri string, body interface{}, params url.Values) (*Request, error) {
method = strings.ToUpper(method)
if body != nil && (method != "POST" && method != "PUT") {
return nil, fmt.Errorf("%s method does not accept body", method)
}
var buf io.Reader
if body != nil {
b, ok := body.([]byte)
if ok {
buf = bytes.NewBuffer(b)
} else {
body, err := toURL(body)
if err != nil {
return nil, err
}
buf = strings.NewReader(body.Encode())
}
}
req, err := http.NewRequest(method, joinURL(uri, params), buf)
if method == "POST" || method == "PUT" {
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
}
rr := Request(*req)
return &rr, err
}
func (req *Request) Do() (*Response, error) {
rr, err := http.DefaultClient.Do((*http.Request)(req))
if err != nil {
return nil, err
}
return (*Response)(rr), nil
}
func (res *Response) ToJSON(i interface{}) error {
defer res.Body.Close()
if c := res.Header.Get("Content-Type"); !strings.Contains(c, "application/json") {
return fmt.Errorf("Unexpected Content-Type, got %s", c)
}
reader := bufio.NewReader(res.Body)
buf, _ := ioutil.ReadAll(reader)
err := json.Unmarshal(buf, i)
//fmt.Printf("%s\n", buf)
//err := json.NewDecoder(res.Body).Decode(v)
return err
}
type DataErrResponse struct {
Error map[string]string
}
func (res *Response) ToErr() (*DataErrResponse, error) {
v := &DataErrResponse{}
err := res.ToJSON(v)
return v, err
}
func toURL(query interface{}) (url.Values, error) {
switch vv := query.(type) {
case url.Values:
return query.(url.Values), nil
case map[string]string:
val := make(url.Values, len(vv))
for k, v := range vv {
val.Add(k, v)
}
return val, nil
default:
s := reflect.ValueOf(query)
t := reflect.TypeOf(query)
val := make(url.Values, s.NumField())
for i := 0; i < s.NumField(); i++ {
val.Add(strings.ToLower(t.Field(i).Name), fmt.Sprintf("%v", s.Field(i).Interface()))
}
return val, nil
}
}
func joinURL(endpoint string, args url.Values) string {
var params string
if args != nil && len(args) > 0 {
params = "?" + args.Encode()
}
return endpoint + params
}