-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathactuator.go
95 lines (86 loc) · 2.36 KB
/
actuator.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
88
89
90
91
92
93
94
95
package actuator
import (
"fmt"
"net/http"
)
// Endpoints enumeration
const (
Env = iota
Info
Metrics
Ping
Shutdown
ThreadDump
)
// AllEndpoints is the list of endpoints supported
var AllEndpoints = []int{Env, Info, Metrics, Ping, Shutdown, ThreadDump}
// Config is the set of configurable parameters for the actuator setup
type Config struct {
Endpoints []int
Env string
Name string
Port int
Version string
}
func (config *Config) validate() {
for _, endpoint := range config.Endpoints {
if !isValidEndpoint(endpoint) {
panic(fmt.Errorf("invalid endpoint %d provided", endpoint))
}
}
}
// Default is used to fill the default configs in case of any missing ones
func (config *Config) setDefaults() {
if config.Endpoints == nil {
config.Endpoints = AllEndpoints
}
}
// GetActuatorHandler is used to get the handler function for the actuator endpoints
// This single handler is sufficient for handling all the endpoints.
func GetActuatorHandler(config *Config) http.HandlerFunc {
if config == nil {
config = &Config{}
}
handleConfigs(config)
handlerMap := getHandlerMap(config)
return func(writer http.ResponseWriter, request *http.Request) {
if request.Method != http.MethodGet {
// method not allowed for the requested resource
sendStringResponse(writer, http.StatusMethodNotAllowed, methodNotAllowedError)
return
}
endpoint := fmt.Sprintf("/%s", getLastStringAfterDelimiter(request.URL.Path, slash))
if handler, ok := handlerMap[endpoint]; ok {
handler(writer, request)
return
}
// incorrect endpoint
// or endpoint not enabled
sendStringResponse(writer, http.StatusNotFound, notFoundError)
}
}
func handleConfigs(config *Config) {
config.validate()
config.setDefaults()
}
func getHandlerMap(config *Config) map[string]http.HandlerFunc {
handlerMap := make(map[string]http.HandlerFunc, len(config.Endpoints))
for _, e := range config.Endpoints {
// now one by one add the handler of each endpoint
switch e {
case Env:
handlerMap[envEndpoint] = getEnvHandler(config)
case Info:
handlerMap[infoEndpoint] = getInfoHandler(config)
case Metrics:
handlerMap[metricsEndpoint] = handleMetrics
case Ping:
handlerMap[pingEndpoint] = handlePing
case Shutdown:
handlerMap[shutdownEndpoint] = handleShutdown
case ThreadDump:
handlerMap[threadDumpEndpoint] = handleThreadDump
}
}
return handlerMap
}