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 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
|
// Copyright 2020 PingCAP, Inc.
//
// 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package utils
import (
"context"
"crypto/tls"
"fmt"
"io"
"net"
"net/http"
"net/url"
"os"
"path/filepath"
"time"
)
// HTTPClient is a wrap of http.Client
type HTTPClient struct {
client *http.Client
header http.Header
}
// NewHTTPClient returns a new HTTP client with timeout and HTTPS support
func NewHTTPClient(timeout time.Duration, tlsConfig *tls.Config) *HTTPClient {
if timeout < time.Second {
timeout = 10 * time.Second // default timeout is 10s
}
tr := &http.Transport{
TLSClientConfig: tlsConfig,
Dial: (&net.Dialer{Timeout: 3 * time.Second}).Dial,
}
// prefer to use the inner http proxy
httpProxy := os.Getenv("TIUP_INNER_HTTP_PROXY")
if len(httpProxy) == 0 {
httpProxy = os.Getenv("HTTP_PROXY")
}
if len(httpProxy) > 0 {
if proxyURL, err := url.Parse(httpProxy); err == nil {
tr.Proxy = http.ProxyURL(proxyURL)
}
}
return &HTTPClient{
client: &http.Client{
Timeout: timeout,
Transport: tr,
},
}
}
// SetRequestHeader set http request header
func (c *HTTPClient) SetRequestHeader(key, value string) {
if c.header == nil {
c.header = http.Header{}
}
c.header.Add(key, value)
}
// Get fetch an URL with GET method and returns the response
func (c *HTTPClient) Get(ctx context.Context, url string) ([]byte, error) {
data, _, err := c.GetWithStatusCode(ctx, url)
return data, err
}
// GetWithStatusCode fetch a URL with GET method and returns the response, also the status code.
func (c *HTTPClient) GetWithStatusCode(ctx context.Context, url string) ([]byte, int, error) {
var statusCode int
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, statusCode, err
}
req.Header = c.header
if ctx != nil {
req = req.WithContext(ctx)
}
res, err := c.client.Do(req)
if err != nil {
return nil, statusCode, err
}
defer res.Body.Close()
data, err := checkHTTPResponse(res)
return data, res.StatusCode, err
}
// Download fetch an URL with GET method and Download the response to filePath
func (c *HTTPClient) Download(ctx context.Context, url, filePath string) error {
// IsExist
if IsExist(filePath) {
return fmt.Errorf("target file %s already exists", filePath)
}
if err := MkdirAll(filepath.Dir(filePath), 0755); err != nil {
return err
}
// create target file
f, err := os.Create(filePath)
if err != nil {
return err
}
defer f.Close()
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return err
}
req.Header = c.header
if ctx != nil {
req = req.WithContext(ctx)
}
res, err := c.client.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
_, err = io.Copy(f, res.Body)
if err != nil {
return err
}
return nil
}
// Post send a POST request to the url and returns the response
func (c *HTTPClient) Post(ctx context.Context, url string, body io.Reader) ([]byte, error) {
data, _, err := c.PostWithStatusCode(ctx, url, body)
return data, err
}
// PostWithStatusCode send a POST request to the url and returns the response, also the http status code.
func (c *HTTPClient) PostWithStatusCode(ctx context.Context, url string, body io.Reader) ([]byte, int, error) {
var statusCode int
req, err := http.NewRequest("POST", url, body)
if err != nil {
return nil, statusCode, err
}
if c.header == nil {
req.Header.Set("Content-Type", "application/json")
} else {
req.Header = c.header
}
if ctx != nil {
req = req.WithContext(ctx)
}
res, err := c.client.Do(req)
if err != nil {
return nil, statusCode, err
}
defer res.Body.Close()
data, err := checkHTTPResponse(res)
return data, res.StatusCode, err
}
// Put send a PUT request to the url and returns the response, also the status code
func (c *HTTPClient) Put(ctx context.Context, url string, body io.Reader) ([]byte, int, error) {
var statusCode int
req, err := http.NewRequest("PUT", url, body)
if err != nil {
return nil, statusCode, err
}
if c.header == nil {
req.Header.Set("Content-Type", "application/json")
} else {
req.Header = c.header
}
if ctx != nil {
req = req.WithContext(ctx)
}
resp, err := c.client.Do(req)
if err != nil {
return nil, statusCode, err
}
defer resp.Body.Close()
b, err := checkHTTPResponse(resp)
statusCode = resp.StatusCode
return b, statusCode, err
}
// Delete send a DELETE request to the url and returns the response and status code.
func (c *HTTPClient) Delete(ctx context.Context, url string, body io.Reader) ([]byte, int, error) {
var statusCode int
req, err := http.NewRequest("DELETE", url, body)
if err != nil {
return nil, statusCode, err
}
if ctx != nil {
req = req.WithContext(ctx)
}
res, err := c.client.Do(req)
if err != nil {
return nil, statusCode, err
}
defer res.Body.Close()
b, err := checkHTTPResponse(res)
statusCode = res.StatusCode
return b, statusCode, err
}
// Client returns the http.Client
func (c *HTTPClient) Client() *http.Client {
return c.client
}
// WithClient uses the specified HTTP client
func (c *HTTPClient) WithClient(client *http.Client) *HTTPClient {
c.client = client
return c
}
// checkHTTPResponse checks if an HTTP response is with normal status codes
func checkHTTPResponse(res *http.Response) ([]byte, error) {
body, err := io.ReadAll(res.Body)
if err != nil {
return nil, err
}
if res.StatusCode < 200 || res.StatusCode >= 400 {
return body, fmt.Errorf("error requesting %s, response: %s, code %d",
res.Request.URL, string(body), res.StatusCode)
}
return body, nil
}
|