-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoptions.go
100 lines (81 loc) · 2.41 KB
/
options.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
96
97
98
99
100
package box
import (
"net/http"
"os"
"github.com/labstack/echo-contrib/echoprometheus"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"gopkg.in/yaml.v3"
)
// Option is a modifier function which can alter the provided functionality of a Box.
type Option func(*Box)
// WithConfig configures the Box with the given Config.
func WithConfig(config Config) Option {
return func(box *Box) {
box.Config = config
}
}
// WithConfigFromPath reads a configuration file from the given path, decodes it from YAML and calls WithConfig.
// Panics if the file can not be opened or decoded.
func WithConfigFromPath(path string) Option {
return func(box *Box) {
file, err := os.Open(path)
if err != nil {
panic(err)
}
defer file.Close()
var wrapper configWrapper
err = yaml.NewDecoder(file).Decode(&wrapper)
if err != nil {
panic(err)
}
WithConfig(wrapper.Config)(box)
}
}
// WithGlobalLogger sets the global slog logger to the Box's logger.
func WithGlobalLogger() Option {
return func(box *Box) {
box.loggerGlobal = true
}
}
// WithWebServer enables the web server functionality provided by WebServer.
func WithWebServer() Option {
return func(box *Box) {
box.WebServer = &WebServer{
Echo: echo.New(),
defaultLivenessProbe: func(c echo.Context) error {
return c.NoContent(http.StatusOK)
},
defaultReadinessProbe: func(c echo.Context) error {
return c.NoContent(http.StatusOK)
},
}
box.WebServer.HideBanner = true
box.WebServer.HidePort = true
if box.Config.ListenAddress == "" {
box.Config.ListenAddress = ":8000"
}
box.WebServer.Use(middleware.Recover(), echoprometheus.NewMiddleware("box_webserver"))
box.WebServer.GET("/metrics", echoprometheus.NewHandler())
box.WebServer.GET("/healthz", box.WebServer.defaultLivenessProbe)
box.WebServer.GET("/readyz", box.WebServer.defaultReadinessProbe)
}
}
// WithLivenessProbe allows to override the default liveness probe of the WebServer.
func WithLivenessProbe(probe func(c echo.Context) error) Option {
return func(box *Box) {
if box.WebServer == nil {
WithWebServer()(box)
}
box.WebServer.GET("/healthz", probe)
}
}
// WithReadinessProbe allows to override the default readiness probe of the WebServer.
func WithReadinessProbe(probe func(c echo.Context) error) Option {
return func(box *Box) {
if box.WebServer == nil {
WithWebServer()(box)
}
box.WebServer.GET("/readyz", probe)
}
}