-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathclient.go
73 lines (63 loc) · 1.24 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
package main
import (
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"strings"
"time"
)
var (
defaultInterval = time.Second * 5
)
type client struct {
token string
targetURL string
client http.Client
interval time.Duration
log *log.Logger
}
func newClient(targetURL, tokenFile string) (*client, error) {
_, err := url.Parse(targetURL)
if err != nil {
return nil, err
}
rawToken, err := ioutil.ReadFile(tokenFile)
if err != nil {
return nil, err
}
return &client{
targetURL: targetURL,
token: strings.TrimSpace(string(rawToken)),
interval: defaultInterval,
log: log.New(os.Stderr, "", log.LstdFlags),
}, nil
}
func (c *client) run() error {
c.log.Printf("start client: %s", c.targetURL)
for {
err := c.call()
if err != nil {
c.log.Println(err)
}
time.Sleep(c.interval)
}
}
func (c *client) call() error {
req, err := http.NewRequest("GET", c.targetURL, nil)
if err != nil {
return err
}
req.Header.Add("Authorization", "Bearer "+c.token)
resp, err := c.client.Do(req)
if err != nil {
return err
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
c.log.Printf("target=%s, status=%d, response: '%s'", c.targetURL, resp.StatusCode, string(body))
return nil
}