-
Notifications
You must be signed in to change notification settings - Fork 2
/
serve.go
84 lines (76 loc) · 2 KB
/
serve.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 goss
import (
"bytes"
"log"
"net/http"
"sync"
"time"
"github.com/SimonBaeumer/goss/outputs"
"github.com/SimonBaeumer/goss/system"
"github.com/SimonBaeumer/goss/util"
"github.com/fatih/color"
"github.com/patrickmn/go-cache"
)
//TODO: Maybe separating handler and server?
// HealthHandler creates a new handler for the health endpoint
type HealthHandler struct {
RunTimeConfig GossRunTime
GossConfig GossConfig
Sys *system.System
Outputer outputs.Outputer
Cache *cache.Cache
GossMu *sync.Mutex
ContentType string
MaxConcurrent int
ListenAddr string
FormatOptions []string
}
// Serve creates a new endpoint and starts the http server
func (h *HealthHandler) Serve(endpoint string) {
color.NoColor = true
http.Handle(endpoint, h)
log.Printf("Starting to listen on: %s", h.ListenAddr)
log.Fatal(http.ListenAndServe(h.ListenAddr, nil))
}
type res struct {
exitCode int
b bytes.Buffer
}
//ServeHTTP fulfills the handler interface and is called as a handler on the
//health check request.
func (h HealthHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
outputConfig := util.OutputConfig{
FormatOptions: h.FormatOptions,
}
log.Printf("%v: requesting health probe", r.RemoteAddr)
var resp res
tmp, found := h.Cache.Get("res")
if found {
resp = tmp.(res)
} else {
h.GossMu.Lock()
defer h.GossMu.Unlock()
tmp, found := h.Cache.Get("res")
if found {
resp = tmp.(res)
} else {
h.Sys = system.New()
log.Printf("%v: Stale Cache, running tests", r.RemoteAddr)
iStartTime := time.Now()
out := validate(h.Sys, h.GossConfig, h.MaxConcurrent)
var b bytes.Buffer
exitCode := h.Outputer.Output(&b, out, iStartTime, outputConfig)
resp = res{exitCode: exitCode, b: b}
h.Cache.Set("res", resp, cache.DefaultExpiration)
}
}
if h.ContentType != "" {
w.Header().Set("Content-Type", h.ContentType)
}
if resp.exitCode == 0 {
resp.b.WriteTo(w)
} else {
w.WriteHeader(http.StatusServiceUnavailable)
resp.b.WriteTo(w)
}
}