/
request.go
118 lines (104 loc) · 2.15 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package v2
import (
"bytes"
"encoding/json"
"io/ioutil"
"net/http"
)
type httpMethodStruct struct {
GET string
POST string
}
var HttpMethod = httpMethodStruct{
GET: "GET",
POST: "POST",
}
type Request struct {
Url string
Method string
Body string
BodyBuffer *bytes.Buffer
Headers map[string]string
Client *http.Client
}
func NewRequest() *Request {
r := &Request{
Url: "",
Method: HttpMethod.GET,
Headers: map[string]string{},
}
r.SetHttpClient()
return r
}
func (r *Request) SetHttpClient() {
r.Client = &http.Client{}
}
// Json() prettifies json byte data and returns string
func (r *Request) Json(data []byte) string {
j := &bytes.Buffer{}
err := json.Indent(j, data, "", " ")
// invalid json format
if err != nil {
return string(data)
}
return string(j.Bytes())
}
func (r *Request) ParseJson(s string) *bytes.Buffer {
b := []byte(s)
j := &bytes.Buffer{}
err := json.Indent(j, b, "", " ")
// not valid json
if err != nil {
return bytes.NewBufferString(s)
}
return j
}
// ParseHeaders() parses request headers: map(key: value)
// into string("key:value") and returns parsed string
func (r *Request) ParseHeaders() string {
s := ""
if len(r.Headers) == 0 {
return " + No headers\r\n"
} else {
for k, v := range r.Headers {
s += " + " + k + ": " + v + "\r\n"
}
return s
}
}
func (r *Request) ParseHeadersOptions() []string {
s := []string{"+ Add new"}
if len(r.Headers) != 0 {
for k, v := range r.Headers {
s = append(s, "- "+k+": "+v)
}
}
return s
}
func (r *Request) Send() ([]byte, string, error) {
req, err := (func() (*http.Request, error) {
if r.Method == HttpMethod.GET {
req, err := http.NewRequest(r.Method, r.Url, nil)
return req, err
} else {
req, err := http.NewRequest(r.Method, r.Url, bytes.NewBufferString(r.Body))
return req, err
}
})()
if err != nil {
return nil, "", err
}
for k, v := range r.Headers {
req.Header.Add(k, v)
}
res, err := r.Client.Do(req)
if err != nil {
return nil, "", err
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, "", err
}
return body, res.Status, nil
}