-
Notifications
You must be signed in to change notification settings - Fork 0
/
web.go
78 lines (66 loc) · 2.08 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
// 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"
)
// 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 {
return &App{
ContextMux: httptreemux.NewContextMux(),
shutdown: shutdown,
mw: mw,
}
}
// SignalShutdown is used to gracefully shut down 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, group 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) {
// Pull the context from the request and
// use it as a separate parameter.
ctx := r.Context()
// Set the context with the required values to
// process the request.
v := Values{
TraceID: uuid.New().String(),
Now: time.Now(),
}
ctx = context.WithValue(ctx, key, &v)
// Call the wrapped handler functions.
if err := handler(ctx, w, r); err != nil {
a.SignalShutdown()
return
}
}
finalPath := path
if group != "" {
finalPath = "/" + group + path
}
a.ContextMux.Handle(method, finalPath, h)
}