-
Notifications
You must be signed in to change notification settings - Fork 7
/
endpoint.go
87 lines (81 loc) · 2.03 KB
/
endpoint.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
package main
import (
"errors"
"net/http"
"net/http/httputil"
"net/url"
"time"
log "github.com/sirupsen/logrus"
)
// Endpoint struct containing everything needed for a new endpoint
type Endpoint struct {
Active bool
Address *url.URL
Proxy *httputil.ReverseProxy
Registered string
Available time.Time
}
// isActive returns a bool if the endpiont is active or not
func (e Endpoint) isActive() bool {
return e.Active
}
// HealthCheck performs a basic http check based on a positive(<500) status code
func (e *Endpoint) HealthCheck(healthCheckURL string) {
previousStatus := e.isActive()
statusCode := 500
if resp, err := http.Get(e.Address.String() + "/" + healthCheckURL); err != nil {
// Something is up ... disable this endpoint
e.Active = false
} else {
// Woot! Good to go ...
statusCode = resp.StatusCode
if resp.StatusCode >= 500 {
e.Active = false
} else {
e.Active = true
}
}
log.WithFields(log.Fields{
"previous": previousStatus,
"current": e.Active,
}).Debug(e.Registered)
if e.Active != previousStatus {
if e.Active {
// Whew, we came back online
log.WithFields(
log.Fields{
"URL": e.Address.String(),
}).Info("Up")
e.Available = time.Now()
} else {
// BOO HISS!
log.WithFields(
log.Fields{
"URL": e.Address.String(),
"Status": statusCode,
}).Error("Down")
}
}
}
// NewEndpoint creates new endpoints to forward traffic to
func NewEndpoint(base, address string, checkHealth bool, healthURL string) (*Endpoint, error) {
parsedAddress, err := url.Parse(address)
if err != nil {
log.WithFields(log.Fields{"url": parsedAddress}).Error("Problem parsing URL")
return nil, errors.New("Problem parsing URL " + address)
}
e := &Endpoint{
Address: parsedAddress,
Proxy: httputil.NewSingleHostReverseProxy(parsedAddress),
Active: true,
Available: time.Now(),
Registered: base,
}
if checkHealth {
e.HealthCheck(healthURL)
} else {
// Make it active regardless. Godspeed developer :D
e.Active = true
}
return e, nil
}