-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
73 lines (60 loc) · 1.71 KB
/
http.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
package utorrent
import (
"bytes"
"fmt"
"net/http"
)
func (c *Client) url(path string) string {
if path == "" || path[0:1] != "/" {
path = fmt.Sprintf("/%s", path)
}
if c.token != "" {
path = fmt.Sprintf("%s&token=%s", path, c.token)
}
return fmt.Sprintf("%s%s", c.API, path)
}
func (c *Client) request(method, path string, payload []byte, headers *http.Header) (*http.Response, error) {
if c == nil {
return nil, fmt.Errorf("Cannot make a request with a nil client")
}
in := bytes.NewBuffer(payload)
req, err := http.NewRequest(method, c.url(path), in)
if err != nil {
return nil, err
}
req.SetBasicAuth(c.Username, c.Password)
if headers != nil {
for header, values := range *headers {
for _, value := range values {
req.Header.Add(header, value)
}
}
}
res, err := c.user_agent.Do(req)
if err != nil {
return nil, err
}
return res, nil
}
func (c *Client) post(path string, payload []byte, headers *http.Header) (*http.Response, error) {
return c.request("POST", path, payload, headers)
}
func (c *Client) put(path string, payload []byte, headers *http.Header) (*http.Response, error) {
return c.request("PUT", path, payload, headers)
}
func (c *Client) get(path string, headers *http.Header) (*http.Response, error) {
return c.request("GET", path, nil, headers)
}
func (c *Client) delete(path string, headers *http.Header) (*http.Response, error) {
return c.request("DELETE", path, nil, headers)
}
func (c *Client) action(action string, hash string, headers *http.Header) error {
res, err := c.get(fmt.Sprintf("/?action=%s&hash=%s", action, hash), headers)
if err != nil {
return err
}
if res.StatusCode != 200 {
return fmt.Errorf("error status: %s", res.Status)
}
return nil
}