forked from rs/xhandler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chain_example_test.go
35 lines (27 loc) · 932 Bytes
/
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
package xhandler_test
import (
"fmt"
"net/http"
"time"
"github.com/rs/cors"
"github.com/rs/xhandler"
"golang.org/x/net/context"
)
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!")
})))
}