-
Notifications
You must be signed in to change notification settings - Fork 0
/
httpclient.go
55 lines (43 loc) · 1.19 KB
/
httpclient.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
package main
import (
"bytes"
"io/ioutil"
"net/http"
"github.com/op/go-logging"
)
type IHttpClient interface {
//PostMeasurement(ctx context.Context, thing *Thing, value string)
PostString(url, body string, username *string, password *string)
}
type HttpClient struct {
log *logging.Logger
client *http.Client
}
func NewHttpClient(log *logging.Logger) IHttpClient {
httpClient := &HttpClient{log: log}
httpClient.client = &http.Client{}
return httpClient
}
func (c *HttpClient) PostString(url, body string, username *string, password *string) {
c.log.Debugf("Http POST to %s", url)
req, err := http.NewRequest("POST", url, bytes.NewReader([]byte(body)))
if err != nil {
c.log.Errorf("Http Post failed (%s)", err.Error())
return
}
if username != nil && password != nil {
req.SetBasicAuth(*username, *password)
}
res, err := c.client.Do(req)
if err != nil {
c.log.Errorf("Http Post failed (%s)", err.Error())
return
}
response, err := ioutil.ReadAll(res.Body)
if err != nil {
c.log.Errorf("Http Post failed (%s)", err.Error())
}
res.Body.Close()
c.log.Debugf("Http post response status code: %d", res.StatusCode)
c.log.Debugf("Http post response body: %s", response)
}