-
Notifications
You must be signed in to change notification settings - Fork 12
/
http.go
139 lines (118 loc) · 3.35 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
// Copyright 2019 The New York Times Company
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package internal
import (
"bytes"
"context"
"crypto/tls"
"fmt"
"io"
"net/http"
"time"
"github.com/hashicorp/go-retryablehttp"
)
// HTTPRequestConfig type
type HTTPRequestConfig struct {
Method string
URL string
QueryParams map[string]string
Headers map[string]string
BasicAuthUsername string
BasicAuthPassword string
Body io.Reader
TimeoutSeconds time.Duration
SkipCertVerification bool
MaxRetries int
RetryCallback func(ctx context.Context, resp *http.Response, err error) (bool, error)
}
// SendHTTPRequest sends an HTTP request and returns response body and status
func SendHTTPRequest(config *HTTPRequestConfig) (*http.Response, []byte, error) {
// Check input
if config == nil {
return nil, nil, fmt.Errorf("config is nil")
}
if len(config.Method) <= 0 {
return nil, nil, fmt.Errorf("method is required")
}
if len(config.URL) <= 0 {
return nil, nil, fmt.Errorf("URL is required")
}
if config.TimeoutSeconds == 0 {
config.TimeoutSeconds = 10
}
// Create request
req, err := retryablehttp.NewRequest(
config.Method,
config.URL,
config.Body,
)
if err != nil {
return nil, nil, err
}
// Query params
if len(config.QueryParams) > 0 {
q := req.URL.Query()
for k, v := range config.QueryParams {
q.Add(k, v)
}
req.URL.RawQuery = q.Encode()
}
// Host header
// https://github.com/golang/go/issues/7682
if len(config.Headers["host"]) > 0 {
req.Host = config.Headers["host"]
}
// BasicAuth header
if len(config.BasicAuthUsername) > 0 || len(config.BasicAuthPassword) > 0 {
req.SetBasicAuth(config.BasicAuthUsername, config.BasicAuthPassword)
}
// Other headers
for k, v := range config.Headers {
req.Header.Add(k, v)
}
client := retryablehttp.Client{
HTTPClient: &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
Transport: &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: config.SkipCertVerification},
},
Timeout: time.Duration(config.TimeoutSeconds * time.Second),
},
}
// Enable retries
if config.MaxRetries > 0 {
client.RetryMax = config.MaxRetries
client.CheckRetry = config.RetryCallback
client.Backoff = retryablehttp.DefaultBackoff
} else {
// Don't retry requests
client.CheckRetry = func(ctx context.Context, resp *http.Response, inErr error) (bool, error) { return false, nil }
}
// Start sending request
resp, err := client.Do(req)
if err != nil {
return nil, nil, err
}
// Release resource when done
defer resp.Body.Close()
// Read body into a buffer
buf := new(bytes.Buffer)
_, err = buf.ReadFrom(resp.Body)
if err != nil {
return resp, nil, err
}
return resp, buf.Bytes(), nil
}