-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
104 lines (84 loc) · 2.15 KB
/
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
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
package client
import (
"fmt"
"io"
"log"
"net/http"
"net/url"
"strings"
)
type Client struct {
BaseURL *url.URL
Client *http.Client
ReqModifiers []func(*http.Request)
}
func New(baseURL string) *Client {
parsedURL, err := url.Parse(baseURL)
if err != nil {
log.Println(fmt.Sprintf("Error parsing URL: %s", baseURL), err)
return nil
}
return &Client{
BaseURL: parsedURL,
Client: &http.Client{},
ReqModifiers: make([]func(*http.Request), 0),
}
}
func (c *Client) SetHeader(key, value string) *Client {
headers := func(req *http.Request) {
req.Header.Add(key, value)
}
c.ReqModifiers = append(c.ReqModifiers, headers)
return c
}
func (c *Client) SetHeadersFromObject(headers *http.Header) *Client {
for k, v := range *headers {
c.SetHeader(k, v[0])
}
return c
}
func (c *Client) SetBody(body string) *Client {
contentType := http.DetectContentType([]byte(body))
modifier := func(req *http.Request) {
req.Body = io.NopCloser(strings.NewReader(body))
if req.Header.Get("Content-Type") == "" {
req.Header.Set("Content-Type", contentType)
}
}
c.ReqModifiers = append(c.ReqModifiers, modifier)
return c
}
func (c *Client) sendRequest(method, endpoint string) (*http.Response, error) {
url, err := c.BaseURL.Parse(endpoint)
if err != nil {
return nil, err
}
req, err := http.NewRequest(method, url.String(), nil)
if err != nil {
log.Println("Request Error:", err)
return nil, err
}
for _, reqModifier := range c.ReqModifiers {
reqModifier(req)
}
c.ReqModifiers = make([]func(*http.Request), 0)
return c.Client.Do(req)
}
func (c *Client) Fetch(method string, path string) ([]byte, error) {
log.Println("Sending request to " + path)
var response *http.Response = nil
var responseError error
response, responseError = c.sendRequest(method, path)
if responseError != nil {
log.Println("Response Error:", responseError)
return nil, responseError
}
defer response.Body.Close()
log.Println("Response Status:", response.Status)
responseBody, err := io.ReadAll(response.Body)
if err != nil {
log.Println("Response Body Error:", responseError)
return nil, err
}
return responseBody, nil
}