generated from bool64/go-template
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhttp.go
97 lines (79 loc) · 2.48 KB
/
http.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
package brick
import (
"context"
"errors"
"fmt"
"net"
"net/http"
"time"
"github.com/bool64/prom-stats"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/swaggest/openapi-go/openapi3"
"github.com/swaggest/rest/web"
"github.com/swaggest/swgui"
swgv5 "github.com/swaggest/swgui/v5cdn"
)
// NewBaseWebService initializes default http router.
func NewBaseWebService(l *BaseLocator) *web.Service {
// Create router.
r := web.NewService(openapi3.NewReflector(), l.HTTPServiceOptions...)
// Setup middlewares.
r.Wrap(l.HTTPServerMiddlewares...)
if pt, ok := l.StatsTracker().(*prom.Tracker); ok {
r.Method(http.MethodGet, "/metrics", promhttp.HandlerFor(pt.PrometheusRegistry(), promhttp.HandlerOpts{}))
}
if l.BaseConfig.Debug.DevTools {
MountDevPortal(r.Wrapper, l)
}
// Swagger UI endpoint at /docs.
r.Docs("/docs", func(title, schemaURL, basePath string) http.Handler {
cfg := swgui.Config{}
cfg.Title = title
cfg.BasePath = basePath
cfg.SwaggerJSON = schemaURL
for _, o := range l.SwaggerUIOptions {
o(&cfg)
}
return swgv5.NewHandlerWithConfig(cfg)
})
return r
}
// StartHTTPServer starts HTTP server with provided handler
// in a goroutine and returns listening addr or error.
//
// Server will listen at BaseConfig.HTTPListenAddr, if the value
// is empty free random port will be used.
//
// Server will be gracefully stopped on service locator shutdown.
func (l *BaseLocator) StartHTTPServer(handler http.Handler) (string, error) {
cfg := l.BaseConfig
if cfg.HTTPListenAddr == "" || cfg.HTTPListenAddr == ":0" {
cfg.HTTPListenAddr = "127.0.0.1:0"
}
listener, err := net.Listen("tcp", cfg.HTTPListenAddr)
if err != nil {
return "", fmt.Errorf("failed to start http server: %w", err)
}
// Initialize HTTP server.
srv := http.Server{
Handler: handler,
ReadHeaderTimeout: 10 * time.Second,
}
// Start HTTP server.
l.CtxdLogger().Important(context.Background(), fmt.Sprintf("starting server, Swagger UI at http://%s/docs",
listener.Addr().String()))
go func() {
if err := srv.Serve(listener); err != nil && !errors.Is(err, http.ErrServerClosed) {
l.CtxdLogger().Error(context.Background(), err.Error())
l.Shutdown()
}
}()
// Wait for termination signal and HTTP shutdown finished.
l.OnShutdown("http", func() {
err := srv.Shutdown(context.Background())
if err != nil {
l.CtxdLogger().Error(context.Background(), "failed to shutdown http", "error", err.Error())
}
})
return listener.Addr().String(), nil
}