-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
191 lines (161 loc) · 4.13 KB
/
http.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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
// Copyright 2019 Seamia Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"path"
"strings"
"time"
"github.com/seamia/libs/printer"
)
func call(relativeUrl, verb, data string) {
u, err := url.Parse(expand(baseUrl))
quitOnError(err, "Parsing url [%s]", baseUrl)
u.Path = path.Join(u.Path, expand(relativeUrl))
fullUrl := u.String()
if generateCurlCommands {
produceCurlCommand(fullUrl, verb, data)
} else {
data = loadExternalFile(data)
var payload io.Reader
if len(data) > 0 {
payload = bytes.NewReader([]byte(data))
}
client := &http.Client{}
request, err := http.NewRequest(strings.ToUpper(verb), fullUrl, payload)
quitOnError(err, "...")
for key, value := range headers {
if len(key) > 0 && len(value) > 0 {
request.Header.Set(key, expand(value))
}
}
request.Header.Set("User-Agent", userAgent)
start := time.Now()
resp, err := client.Do(request)
if collectTimingInfo {
duration := time.Now().Sub(start)
response("the request took %s", duration.String())
}
quitOnError(err, "......")
displayResponse(resp)
}
}
func displayResponse(resp *http.Response) {
if resp == nil {
response("got an empty response")
}
print := responseFailure
if resp.StatusCode < http.StatusBadRequest {
print = responseSuccess
}
// colorPrint(colorResponse, format, a...)
print("Status: %s", resp.Status)
displayHeaders(resp, print)
if resp.Body != nil {
data, err := ioutil.ReadAll(resp.Body)
quitOnError(err, "Ingesting response body")
savedResponse = data
switch getContentType(resp) {
case contentTypeJson:
displayJsonBody(data, print)
default:
displayPlainBody(data, print)
}
} else {
savedResponse = nil
}
// saveResponse(resp)
}
func displayHeaders(resp *http.Response, print printer.Printer) {
const format = "\tHeader: [%s] = [%s]"
if printResponseHeaders && len(resp.Header) > 0 {
for key := range resp.Header {
value := resp.Header.Get(key)
if attentionNeeded(key) {
responseAttention(format, key, value)
} else {
print(format, key, value)
}
}
}
}
func getContentType(resp *http.Response) string {
return lower(resp.Header.Get(headerContentType))
}
func displayPlainBody(data []byte, print printer.Printer) {
if len(data) == 0 {
print("Body is empty.")
} else {
print("Body: %s", string(data))
}
}
func displayJsonBody(data []byte, print printer.Printer) {
if !responsePrettyPrintBody || len(data) == 0 {
displayPlainBody(data, print)
return
}
var blank interface{}
blank = slice{}
if err := json.Unmarshal(data, &blank); err == nil {
if pretty, err := json.MarshalIndent(blank, marshalPrefix, marshalIndent); err == nil {
displayPlainBody(pretty, print)
return
} else {
reportError(err, "marshalling")
}
} else {
reportError(err, "unmarshalling")
}
blank = msi{}
if err := json.Unmarshal(data, &blank); err == nil {
if pretty, err := json.MarshalIndent(blank, marshalPrefix, marshalIndent); err == nil {
displayPlainBody(pretty, print)
return
} else {
reportError(err, "marshalling")
}
} else {
reportError(err, "unmarshalling")
}
displayPlainBody(data, print)
}
func attentionNeeded(key string) bool {
if strings.HasSuffix(lower(key), headerAttentionSuffix) {
return true
}
return false
}
type SavedResponse struct {
Response struct {
Status string `json:"status"`
StatusCode int `json:"status-code"`
Header http.Header `json:"headers"`
} `json:""`
Request struct {
Url string `json:"url"`
Method string `json:"method"`
} `json:""`
}
func saveResponse(resp *http.Response) {
if resp == nil {
return
}
saved := SavedResponse{}
saved.Response.Status = resp.Status
saved.Response.StatusCode = resp.StatusCode
saved.Response.Header = resp.Header
saved.Request.Method = resp.Request.Method
saved.Request.Url = resp.Request.URL.String()
if data, err := json.MarshalIndent(&saved, marshalPrefix, marshalIndent); err == nil {
fmt.Println(string(data))
} else {
fmt.Println(err)
}
}