-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathhttpserver.go
More file actions
109 lines (101 loc) · 3.56 KB
/
Copy pathhttpserver.go
File metadata and controls
109 lines (101 loc) · 3.56 KB
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
101
102
103
104
105
106
107
108
109
package cloudrunner
import (
"context"
"errors"
"fmt"
"log/slog"
"net/http"
"strings"
"go.einride.tech/cloudrunner/cloudserver"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
)
// 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")
}
tracingMiddleware := run.otelTraceMiddleware.HTTPServer
if run.useLegacyTracing {
tracingMiddleware = run.traceMiddleware.HTTPServer
}
defaultMiddlewares := make([]cloudserver.HTTPMiddleware, 0, 7+len(middlewares))
defaultMiddlewares = append(defaultMiddlewares,
run.otelTraceMiddleware.PubsubTraceExtractor,
func(handler http.Handler) http.Handler {
return otelhttp.NewHandler(
handler,
"server",
otelhttp.WithSpanNameFormatter(httpSpanName),
)
},
run.loggerMiddleware.HTTPServer,
tracingMiddleware,
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,
}
}
// httpSpanName returns a span name following the OpenTelemetry HTTP semantic
// conventions: "{method} {route}".
// See https://opentelemetry.io/docs/specs/semconv/http/http-spans/#name
func httpSpanName(_ string, r *http.Request) string {
route := r.URL.Path
if r.Pattern != "" {
// ServeMux patterns may include a method prefix (e.g. "GET /path").
// Strip it so we always use the actual request method — this matters
// when GET patterns match HEAD requests (r.Method=HEAD, r.Pattern="GET /path").
_, path, found := strings.Cut(r.Pattern, " ")
if found {
route = path
} else {
route = r.Pattern
}
}
return r.Method + " " + route
}
// ListenHTTP binds a listener on the configured port and listens for HTTP requests.
func ListenHTTP(ctx context.Context, httpServer *http.Server) error {
run, ok := getRunContext(ctx)
if !ok {
return fmt.Errorf("cloudrunner.ListenHTTP: must be called with a context from cloudrunner.Run")
}
shutdownTimeout := run.serverMiddleware.Config.ShutdownTimeout
shutdown := make(chan struct{})
//nolint:gosec // G118: intentional use of context.Background for graceful shutdown after parent context cancellation
go func() {
<-ctx.Done()
slog.InfoContext(ctx, "HTTPServer shutting down")
shutdownContext, cancel := context.WithTimeout(context.Background(), shutdownTimeout)
defer cancel()
httpServer.SetKeepAlivesEnabled(false)
if err := httpServer.Shutdown(shutdownContext); err != nil {
slog.ErrorContext(ctx, "HTTPServer shutdown error", slog.Any("error", err))
}
close(shutdown)
}()
slog.InfoContext(ctx, "HTTPServer listening", slog.String("address", httpServer.Addr))
err := httpServer.ListenAndServe()
if errors.Is(err, http.ErrServerClosed) && ctx.Err() != nil {
<-shutdown
} else if err != nil {
return err
}
return nil
}