-
Notifications
You must be signed in to change notification settings - Fork 8
/
client.go
89 lines (75 loc) · 1.69 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
package client
import (
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
)
const baseURL string = "https://robot-ws.your-server.de"
const version = "0.1.3"
const userAgent = "hrobot-client/" + version
type Client struct {
Username string
Password string
baseURL string
userAgent string
}
func NewBasicAuthClient(username, password string) RobotClient {
return &Client{
Username: username,
Password: password,
baseURL: baseURL,
userAgent: userAgent,
}
}
func (c *Client) SetBaseURL(baseURL string) {
c.baseURL = baseURL
}
func (c *Client) SetUserAgent(userAgent string) {
c.userAgent = userAgent
}
func (c *Client) GetVersion() string {
return version
}
func (c *Client) doGetRequest(url string) ([]byte, error) {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
bytes, err := c.doRequest(req)
if err != nil {
return nil, err
}
return bytes, nil
}
func (c *Client) doPostFormRequest(url string, formData url.Values) ([]byte, error) {
req, err := http.NewRequest("POST", url, strings.NewReader(formData.Encode()))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
bytes, err := c.doRequest(req)
if err != nil {
return nil, err
}
return bytes, nil
}
func (c *Client) doRequest(req *http.Request) ([]byte, error) {
req.Header.Set("User-Agent", c.userAgent)
req.SetBasicAuth(c.Username, c.Password)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if 200 != resp.StatusCode {
return nil, fmt.Errorf("%s", body)
}
return body, nil
}