-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathchain_example_test.go
86 lines (67 loc) · 2.43 KB
/
chain_example_test.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
package xhandler_test
import (
"fmt"
"net/http"
"strings"
"time"
"context"
"github.com/rs/cors"
"github.com/rs/xhandler"
)
func ExampleChain() {
c := xhandler.Chain{}
// Append a context-aware middleware handler
c.UseC(xhandler.CloseHandler)
// Mix it with a non-context-aware middleware handler
c.Use(cors.Default().Handler)
// Another context-aware middleware handler
c.UseC(xhandler.TimeoutHandler(2 * time.Second))
mux := http.NewServeMux()
// Use c.Handler to terminate the chain with your final handler
mux.Handle("/", c.Handler(xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, "Welcome to the home page!")
})))
// You can reuse the same chain for other handlers
mux.Handle("/api", c.Handler(xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, "Welcome to the API!")
})))
}
func ExampleAddChain() {
c := xhandler.Chain{}
close := xhandler.CloseHandler
cors := cors.Default().Handler
timeout := xhandler.TimeoutHandler(2 * time.Second)
auth := func(next xhandler.HandlerC) xhandler.HandlerC {
return xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
if v := ctx.Value("Authorization"); v == nil {
http.Error(w, "Not authorized", http.StatusUnauthorized)
return
}
next.ServeHTTPC(ctx, w, r)
})
}
c.Add(close, cors, timeout)
mux := http.NewServeMux()
// Use c.Handler to terminate the chain with your final handler
mux.Handle("/", c.Handler(xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, "Welcome to the home page!")
})))
// Create a new chain from an existing one, and add route-specific middleware to it
protected := c.With(auth)
mux.Handle("/admin", protected.Handler(xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, "protected endpoint!")
})))
}
func ExampleIf() {
c := xhandler.Chain{}
// Add a timeout handler only if the URL path matches a prefix
c.UseC(xhandler.If(
func(ctx context.Context, w http.ResponseWriter, r *http.Request) bool {
return strings.HasPrefix(r.URL.Path, "/with-timeout/")
},
xhandler.TimeoutHandler(2*time.Second),
))
http.Handle("/", c.Handler(xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, "Welcome to the home page!")
})))
}