/
client.go
59 lines (49 loc) · 1.41 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
package notifications
import (
"bytes"
"crypto/tls"
"fmt"
"io"
"io/ioutil"
"net/http"
"strings"
"time"
)
type Client struct {
httpClient *http.Client
}
// CreateClient creates a new client with a default timeout
func CreateClient() Client {
client := &http.Client{
Timeout: 10 * time.Second,
}
client.Transport = &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
return Client{httpClient: client}
}
// Request sends an http request and returns error also if response code is NOT 2XX
func (c Client) Request(endpoint string, requestBody string, headers map[string]string) error {
body := bytes.NewBufferString(requestBody)
req, err := http.NewRequest("POST", endpoint, body)
if err != nil {
return fmt.Errorf("new http request: %s %s: %v", "POST", endpoint, err)
}
for k, v := range headers {
req.Header.Add(k, v)
}
resp, err := c.httpClient.Do(req)
if err != nil {
return fmt.Errorf("http request: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode/100 != 2 {
b, _ := ioutil.ReadAll(resp.Body) // try to read response body as well to give user more info why request failed
return fmt.Errorf("%s %s returned %d %s, expected 2xx",
"POST", endpoint, resp.StatusCode, strings.TrimSuffix(string(b), "\n"))
}
if _, err = io.Copy(ioutil.Discard, resp.Body); err != nil {
return fmt.Errorf("read response body: %s %s: %v", "POST", endpoint, err)
}
return nil
}