This repository has been archived by the owner on Jan 13, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 30
/
web.go
93 lines (75 loc) · 2.53 KB
/
web.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
// Package web contains a small web framework extension.
package web
import (
"context"
"net/http"
"os"
"syscall"
"time"
"github.com/dimfeld/httptreemux/v5"
"github.com/google/uuid"
)
// ctxKey represents the type of value for the context key.
type ctxKey int
// KeyValues is how request values are stored/retrieved.
const KeyValues ctxKey = 1
// Values represent state for each request.
type Values struct {
TraceID string
Now time.Time
StatusCode int
}
// A Handler is a type that handles an http request within our own little mini
// framework.
type Handler func(ctx context.Context, w http.ResponseWriter, r *http.Request) error
// App is the entrypoint into our application and what configures our context
// object for each of our http handlers. Feel free to add any configuration
// data/logic on this App struct.
type App struct {
*httptreemux.ContextMux
shutdown chan os.Signal
mw []Middleware
}
// NewApp creates an App value that handle a set of routes for the application.
func NewApp(shutdown chan os.Signal, mw ...Middleware) *App {
// Create an OpenTelemetry HTTP Handler which wraps our router. This will start
// the initial span and annotate it with information about the request/response.
//
// This is configured to use the W3C TraceContext standard to set the remote
// parent if an client request includes the appropriate headers.
// https://w3c.github.io/trace-context/
return &App{
ContextMux: httptreemux.NewContextMux(),
shutdown: shutdown,
mw: mw,
}
}
// SignalShutdown is used to gracefully shutdown the app when an integrity
// issue is identified.
func (a *App) SignalShutdown() {
a.shutdown <- syscall.SIGTERM
}
// Handle sets a handler function for a given HTTP method and path pair
// to the application server mux.
func (a *App) Handle(method string, path string, handler Handler, mw ...Middleware) {
// First wrap handler specific middleware around this handler.
handler = wrapMiddleware(mw, handler)
// Add the application's general middleware to the handler chain.
handler = wrapMiddleware(a.mw, handler)
// The function to execute for each request.
h := func(w http.ResponseWriter, r *http.Request) {
// Set the context with the required values to
// process the request.
v := Values{
TraceID: uuid.New().String(),
Now: time.Now(),
}
ctx := context.WithValue(r.Context(), KeyValues, &v)
// Call the wrapped handler functions.
if err := handler(ctx, w, r); err != nil {
a.SignalShutdown()
return
}
}
a.ContextMux.Handle(method, path, h)
}