-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhealthcheck.go
More file actions
73 lines (66 loc) · 1.91 KB
/
Copy pathhealthcheck.go
File metadata and controls
73 lines (66 loc) · 1.91 KB
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
// Copyright Louis Royer and the NextMN contributors. All rights reserved.
// Use of this source code is governed by a MIT-style license that can be
// found in the LICENSE file.
// SPDX-License-Identifier: MIT
package healthcheck
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"time"
"github.com/sirupsen/logrus"
)
// Healthcheck allows to check status of the node
type Healthcheck struct {
url string
userAgent string
}
// Status of the node
type Status struct {
Ready bool `json:"ready"`
}
// Create a new Healthcheck
func NewHealthcheck(url url.URL, userAgent string) *Healthcheck {
return &Healthcheck{
url: url.String(),
userAgent: userAgent,
}
}
// Run returns an error if the node status is not `ready`
func (h *Healthcheck) Run(ctx context.Context) error {
client := http.Client{
Timeout: 100 * time.Millisecond,
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, h.url, nil)
if err != nil {
logrus.WithError(err).Error("Error while creating http get request")
return err
}
req.Header.Add("User-Agent", h.userAgent)
req.Header.Set("Accept", "application/json")
req.Header.Set("Accept-Charset", "utf-8")
resp, err := client.Do(req)
if err != nil {
logrus.WithFields(logrus.Fields{"remote-server": h.url}).WithError(err).Info("No http response")
return err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
logrus.WithFields(logrus.Fields{"remote-server": h.url}).WithError(err).Info("Http response is not 200 OK")
return err
}
decoder := json.NewDecoder(resp.Body)
var status Status
if err := decoder.Decode(&status); err != nil {
logrus.WithFields(logrus.Fields{"remote-server": h.url}).WithError(err).Info("Could not decode json response")
return err
}
if !status.Ready {
err := fmt.Errorf("server is not ready")
logrus.WithFields(logrus.Fields{"remote-server": h.url}).WithError(err).Info("Server is not ready")
return err
}
return nil
}