-
Notifications
You must be signed in to change notification settings - Fork 2
/
httpserver.go
64 lines (59 loc) · 2.05 KB
/
httpserver.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
package cloudrunner
import (
"context"
"errors"
"fmt"
"log/slog"
"net/http"
"go.einride.tech/cloudrunner/cloudserver"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
"go.uber.org/zap"
)
// HTTPMiddleware is an HTTP middleware.
type HTTPMiddleware = func(http.Handler) http.Handler
// NewHTTPServer creates a new HTTP server preconfigured with middleware for request logging, tracing, etc.
func NewHTTPServer(ctx context.Context, handler http.Handler, middlewares ...HTTPMiddleware) *http.Server {
if handler == nil {
panic("cloudrunner.NewHTTPServer: handler must not be nil")
}
run, ok := getRunContext(ctx)
if !ok {
panic("cloudrunner.NewHTTPServer: must be called with a context from cloudrunner.Run")
}
defaultMiddlewares := []cloudserver.HTTPMiddleware{
func(handler http.Handler) http.Handler {
return otelhttp.NewHandler(handler, "server")
},
run.loggerMiddleware.HTTPServer,
run.traceMiddleware.HTTPServer,
run.requestLoggerMiddleware.HTTPServer,
run.securityHeadersMiddleware.HTTPServer,
run.serverMiddleware.HTTPServer,
}
return &http.Server{
Addr: fmt.Sprintf(":%d", run.config.Runtime.Port),
Handler: cloudserver.ChainHTTPMiddleware(
handler,
append(defaultMiddlewares, middlewares...)...,
),
ReadTimeout: run.serverMiddleware.Config.Timeout,
ReadHeaderTimeout: run.serverMiddleware.Config.Timeout,
WriteTimeout: run.serverMiddleware.Config.Timeout,
IdleTimeout: run.serverMiddleware.Config.Timeout,
}
}
// ListenHTTP binds a listener on the configured port and listens for HTTP requests.
func ListenHTTP(ctx context.Context, httpServer *http.Server) error {
go func() {
<-ctx.Done()
Logger(ctx).Info("HTTPServer shutting down")
if err := httpServer.Shutdown(context.Background()); err != nil {
Logger(ctx).Error("HTTPServer shutdown error", zap.Error(err))
}
}()
slog.InfoContext(ctx, "HTTPServer listening", slog.String("address", httpServer.Addr))
if err := httpServer.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
return err
}
return nil
}