-
Notifications
You must be signed in to change notification settings - Fork 8
/
http_client.go
77 lines (70 loc) · 1.58 KB
/
http_client.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
package utils
import (
"bytes"
"crypto/tls"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
)
type HTTPClient struct {
client *http.Client
body []byte
}
func (h *HTTPClient) New() {
var proxy string
httpProxy := os.Getenv("http_proxy")
httpsProxy := os.Getenv("https_proxy")
if httpProxy != "" {
proxy = httpProxy
} else if httpsProxy != "" {
proxy = httpsProxy
}
proxyURL, err := url.Parse(proxy)
if err != nil {
fmt.Fprintln(os.Stderr, "Error:", err)
os.Exit(1)
}
h.client = &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
MinVersion: tls.VersionTLS12,
MaxVersion: tls.VersionTLS13,
},
},
}
if proxy != "" {
h.client.Transport.(*http.Transport).Proxy = http.ProxyURL(proxyURL)
}
}
func (h *HTTPClient) Do(request *http.Request) (body []byte, err error) {
response, err := h.client.Do(request)
if err != nil {
fmt.Fprintln(os.Stderr, "Error:", err)
os.Exit(1)
}
defer response.Body.Close()
if body, err = io.ReadAll(response.Body); err != nil {
fmt.Fprintln(os.Stderr, "Error:", err)
os.Exit(1)
}
if response.StatusCode != 204 && response.StatusCode != 200 {
err = fmt.Errorf("REST API returned %d %s", response.StatusCode, http.StatusText(response.StatusCode))
}
h.body = body
return
}
func (h *HTTPClient) HandleBody() {
var buffer bytes.Buffer
if err := json.Indent(&buffer, h.body, "", " "); err != nil {
fmt.Fprint(os.Stderr, string(h.body))
} else {
output := buffer.Bytes()
if output[len(output)-1] != '\n' {
output = append(output, '\n')
}
fmt.Fprint(os.Stderr, string(output))
}
}