-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttphealth.go
55 lines (50 loc) · 1.05 KB
/
httphealth.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
package main
import (
"fmt"
"io"
"io/ioutil"
"net/http"
log "github.com/sirupsen/logrus"
)
type HttpCheck struct {
client *http.Client
port int
}
func NewHttpCheck(port int) HttpCheck {
return HttpCheck{
client: http.DefaultClient,
port: port,
}
}
func (hc HttpCheck) Check() Result {
url := fmt.Sprintf("http://127.0.0.1:%d", hc.port)
resp, err := hc.client.Get(url)
if err != nil {
log.WithFields(log.Fields{"error": err}).Warn("error while trying to query HTTP endpoint")
return Result{
healthy: false,
err: err.Error(),
output: "",
}
}
defer func() {
io.Copy(ioutil.Discard, resp.Body)
resp.Body.Close()
}()
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
body := string(bodyBytes)
healthy := true
// Non-2XX
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
log.WithFields(log.Fields{"code": resp.StatusCode}).Warn("invalid response from endpoint")
healthy = false
}
return Result{
healthy: healthy,
err: "",
output: body,
}
}