-
Notifications
You must be signed in to change notification settings - Fork 3
/
ping_client.go
84 lines (74 loc) · 1.95 KB
/
ping_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
package main
import (
"crypto/tls"
"crypto/x509"
"encoding/json"
"io/ioutil"
"log"
"net/http"
"time"
"go.uber.org/zap"
)
// PingClient is a client that can be started
type PingClient interface {
Start()
}
type pingClient struct {
addresses []string
client *http.Client
interval time.Duration
logger *zap.SugaredLogger
}
func (pc *pingClient) Start() {
c := time.Tick(time.Duration(pc.interval) * time.Second)
for range c {
for _, address := range pc.addresses {
pc.pingAddress(address)
}
}
}
func (pc *pingClient) pingAddress(address string) {
response, err := pc.client.Get(address + "/ping")
if err != nil {
pc.logger.Infof("Couldn't ping %s: %s", address, err)
} else {
defer response.Body.Close()
if response.StatusCode != 200 {
pc.logger.Errorf("Got non-ok response code: '%v'", response.StatusCode)
} else {
var pingAnswer string
err := json.NewDecoder(response.Body).Decode(&pingAnswer)
if err != nil {
pc.logger.Errorf("error decoding json response: '%v'", err)
}
pc.logger.Infof("Pinged %s, got response: %s, \"%s\"", address, response.Status, pingAnswer)
}
}
}
// NewPingClient creates a new client for pinging PingServers
func NewPingClient(serverConfig *HTTPConfig, addresses []string, interval time.Duration) PingClient {
logger, err := zap.NewDevelopment()
if err != nil {
log.Fatalf("can't initialize zap logger: %v", err)
}
sugar := logger.Sugar()
client := http.DefaultClient
if serverConfig.caCertFile != "" {
caCert, err := ioutil.ReadFile(serverConfig.caCertFile)
if err != nil {
sugar.Fatal(err)
}
caCertPool, err := x509.SystemCertPool()
if err != nil {
sugar.Fatal(err)
}
caCertPool.AppendCertsFromPEM(caCert)
tlsConfig := &tls.Config{
RootCAs: caCertPool,
}
tlsConfig.BuildNameToCertificate()
transport := &http.Transport{TLSClientConfig: tlsConfig}
client = &http.Client{Transport: transport}
}
return &pingClient{addresses, client, interval, sugar}
}