-
Notifications
You must be signed in to change notification settings - Fork 1
/
http.go
223 lines (192 loc) · 6.77 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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
// MIT License
//
// (C) Copyright [2019-2021] Hewlett Packard Enterprise Development LP
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
// OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
package base
import (
"bytes"
"context"
"crypto/tls"
"encoding/json"
"fmt"
"github.com/hashicorp/go-retryablehttp"
"io/ioutil"
"net/http"
"os"
"time"
)
// Package to slightly abstract some of the most mundane of HTTP interactions. Primary intention is as a JSON
// getter and parser, with the latter being a generic interface that can be converted to a custom structure.
type HTTPRequest struct {
Context context.Context // Context to pass to the underlying HTTP client.
FullURL string // The full URL to pass to the HTTP client.
Method string // HTTP method to use.
Payload []byte // Bytes payload to pass if desired of ContentType.
Auth *Auth // Basic authentication if necessary using Auth struct.
Timeout time.Duration // Timeout for entire transaction.
SkipTLSVerify bool // Ignore TLS verification errors?
ExpectedStatusCode int // Expected HTTP status return code.
ContentType string // HTTP content type of Payload.
}
// These are used to reduce duplication when adding User-Agent headers to requests.
const USERAGENT = "User-Agent"
func GetServiceInstanceName() (string, error) {
return os.Hostname()
}
func SetHTTPUserAgent(req *http.Request, instName string) {
if req == nil {
return
}
//See if this User Agent is already in place
found := false
_, ok := req.Header[USERAGENT]
if ok {
for _, v := range req.Header[USERAGENT] {
if v == instName {
found = true
break
}
}
}
if !found {
req.Header.Add(USERAGENT, instName)
}
}
// NewHTTPRequest creates a new HTTPRequest with default settings.
func NewHTTPRequest(fullURL string) *HTTPRequest {
return &HTTPRequest{
Context: context.Background(),
FullURL: fullURL,
Method: "GET",
Payload: nil,
Auth: nil,
Timeout: 30 * time.Second,
SkipTLSVerify: false,
ExpectedStatusCode: http.StatusOK,
ContentType: "application/json",
}
}
func (request *HTTPRequest) String() string {
return fmt.Sprintf(
"Context: %s, "+
"Method: %s, "+
"Full URL: %s, "+
"Payload: %s, "+
"Auth: (%s), "+
"Timeout: %d, "+
"SkipTLSVerify: %t, "+
"ExpectedStatusCode: %d, "+
"ContentType: %s",
request.Context,
request.Method,
request.FullURL,
string(request.Payload),
request.Auth,
request.Timeout,
request.SkipTLSVerify,
request.ExpectedStatusCode,
request.ContentType)
}
// HTTP basic authentication structure.
type Auth struct {
Username string
Password string
}
// Custom String function to prevent passwords from being printed directly (accidentally) to output.
func (auth Auth) String() string {
return fmt.Sprintf("Username: %s, Password: <REDACTED>", auth.Username)
}
// Functions
// Given a HTTPRequest this function will facilitate the desired operation using the retryablehttp package to gracefully
// retry should the connection fail.
func (request *HTTPRequest) DoHTTPAction() (payloadBytes []byte, err error) {
// Sanity check
if request.FullURL == "" {
err = fmt.Errorf("URL can not be empty")
return
}
// Setup the common HTTP request stuff.
transport := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: request.SkipTLSVerify},
}
client := retryablehttp.NewClient()
client.HTTPClient.Timeout = request.Timeout
client.HTTPClient.Transport = transport
var req *retryablehttp.Request
// If there's a payload, make sure to include it.
if request.Payload == nil {
req, _ = retryablehttp.NewRequest(request.Method, request.FullURL, nil)
} else {
req, _ = retryablehttp.NewRequest(request.Method, request.FullURL, bytes.NewBuffer(request.Payload))
}
// Set the context to the same we were given on the way in.
req = req.WithContext(request.Context)
req.Header.Set("Content-Type", request.ContentType)
if request.Auth != nil {
req.SetBasicAuth(request.Auth.Username, request.Auth.Password)
}
resp, doErr := client.Do(req)
if doErr != nil {
err = fmt.Errorf("unable to do request: %s", doErr)
return
}
// Make sure we get the status code we expect.
if resp.StatusCode != request.ExpectedStatusCode {
err = fmt.Errorf("received unexpected status code: %d", resp.StatusCode)
return
}
// Get the payload.
payloadBytes, readErr := ioutil.ReadAll(resp.Body)
if readErr != nil {
err = fmt.Errorf("unable to read response body: %s", readErr)
return
}
err = resp.Body.Close()
if err != nil {
return
}
return
}
// Returns an interface for the response body for a given request by calling DoHTTPAction and unmarshaling.
// As such, do NOT call this method unless you expect a JSON body in return!
//
// A powerful way to use this function is by feeding its result to the mapstructure package's Decode method:
// v := request.GetBodyForHTTPRequest()
// myTypeInterface := v.(map[string]interface{})
// var myPopulatedStruct MyType
// mapstructure.Decode(myTypeInterface, &myPopulatedStruct)
// In this way you can generically make all your HTTP requests and essentially "cast" the resulting interface to a
// structure of your choosing using it as normal after that point. Just make sure to infer the correct type for `v`.
func (request *HTTPRequest) GetBodyForHTTPRequest() (v interface{}, err error) {
payloadBytes, err := request.DoHTTPAction()
if err != nil {
return
}
stringPayloadBytes := string(payloadBytes)
if stringPayloadBytes != "" {
// If we've made it to here we have all we need, unmarshal.
jsonErr := json.Unmarshal(payloadBytes, &v)
if jsonErr != nil {
err = fmt.Errorf("unable to unmarshal payload: %s", jsonErr)
return
}
}
return
}