-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
76 lines (67 loc) · 2.34 KB
/
server.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
package webbase
import (
"log"
"net/http"
"time"
"github.com/bonsai-oss/mux"
"github.com/getsentry/sentry-go"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/collectors"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
const (
DefaultFunctionAddress = ":8080"
DefaultMetricsAddress = ":8081"
)
var (
FunctionName string
)
// Serve is a helper function to start a server with a single function handler
//
// Deprecated: Use ServeFunction instead
func Serve(name string, functionHandler http.HandlerFunc) {
ServeFunction(name, functionHandler)
}
// ServeFunction starts a server with a single handler function
func ServeFunction(name string, functionHandler http.HandlerFunc, options ...serveOption) {
router := NewRouter()
router.PathPrefix("/").HandlerFunc(functionHandler)
ServeRouter(name, router, options...)
}
// ServeRouter starts a server with a set of routes
func ServeRouter(name string, router *mux.Router, options ...serveOption) {
config := serveConfiguration{
webListenAddress: DefaultFunctionAddress,
serviceListenAddress: DefaultMetricsAddress,
enableServiceListener: true,
healthCheckHandlerFunc: func(responseWriter http.ResponseWriter, _ *http.Request) {
http.Error(responseWriter, "OK", http.StatusOK)
},
sentryClientOptions: sentry.ClientOptions{
TracesSampleRate: 1.0,
EnableTracing: true,
Transport: sentry.NewHTTPSyncTransport(),
},
}
for _, option := range options {
if optionApplyError := option(&config); optionApplyError != nil {
log.Fatalf("failed to apply serveOption: %v", optionApplyError)
}
}
// initialize sentry connection
sentry.Init(config.sentryClientOptions)
defer sentry.Flush(2 * time.Second)
FunctionName = name
if config.enableServiceListener {
go serviceListener(config.serviceListenAddress, config.healthCheckHandlerFunc)
}
err := http.ListenAndServe(config.webListenAddress, router)
log.Fatal(err)
}
// serviceListener starts a server to listen for metrics and health checks
func serviceListener(listenAddress string, healthCheckHandlerFunc http.HandlerFunc) {
prometheus.DefaultRegisterer.Register(collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}))
http.Handle("/metrics", promhttp.Handler())
http.HandleFunc("/health", healthCheckHandlerFunc)
http.ListenAndServe(listenAddress, nil)
}