-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
99 lines (92 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
package main
import (
"encoding/json"
"io"
"net/http"
"net/url"
"path"
"strings"
"time"
"github.com/cenkalti/log"
)
// Client is for reading and writing files on Efes.
type Client struct {
config *Config
log log.Logger
trackerURL *url.URL
httpClient http.Client
drainer bool
}
// NewClient creates a new Client.
func NewClient(cfg *Config) (*Client, error) {
u, err := url.Parse(cfg.Client.TrackerURL)
if err != nil {
return nil, err
}
c := &Client{
config: cfg,
trackerURL: u,
log: log.NewLogger("client"),
}
c.httpClient.Timeout = time.Duration(cfg.Client.SendTimeout)
if cfg.Debug {
c.log.SetLevel(log.DEBUG)
}
return c, nil
}
func (c *Client) request(method, urlPath string, params url.Values, response interface{}) (h http.Header, err error) {
var reqBody io.Reader
if method == http.MethodPost {
reqBody = strings.NewReader(params.Encode())
}
newURL := *c.trackerURL
newURL.Path = path.Join(c.trackerURL.Path, urlPath)
if method == http.MethodGet {
newURL.RawQuery = params.Encode()
}
req, err := http.NewRequest(method, newURL.String(), reqBody) // nolint: noctx
if err != nil {
return
}
if method == http.MethodPost {
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
}
c.log.Debugln("request method:", req.Method, "path:", req.URL.Path, "params:", params)
resp, err := c.httpClient.Do(req)
if err != nil {
return
}
defer resp.Body.Close()
h = resp.Header
err = checkResponseError(resp)
if err != nil {
return
}
if response == nil {
return
}
err = json.NewDecoder(resp.Body).Decode(response)
if err != nil {
return
}
c.log.Debugf("%s got response: %#v", req.URL.Path, response)
return
}
// Delete the key on Efes.
func (c *Client) Delete(key string) error {
form := url.Values{}
form.Add("key", key)
_, err := c.request(http.MethodPost, "delete", form, nil)
return err
}
// Exists checks the existence of a key on Efes.
func (c *Client) Exists(key string) (bool, error) {
_, err := c.getPath(key)
if err != nil {
if errc, ok := err.(*ClientError); ok && errc.Code == http.StatusNotFound {
return false, nil
}
return false, err
}
return true, nil
}