-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathxhandler_example_test.go
68 lines (53 loc) · 1.62 KB
/
xhandler_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
package xhandler_test
import (
"log"
"net/http"
"time"
"context"
"github.com/rs/xhandler"
)
type key int
const contextKey key = 0
func newContext(ctx context.Context, value string) context.Context {
return context.WithValue(ctx, contextKey, value)
}
func fromContext(ctx context.Context) (string, bool) {
value, ok := ctx.Value(contextKey).(string)
return value, ok
}
func ExampleHandle() {
var xh xhandler.HandlerC
xh = xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
value, _ := fromContext(ctx)
w.Write([]byte("Hello " + value))
})
xh = (func(next xhandler.HandlerC) xhandler.HandlerC {
return xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
ctx = newContext(ctx, "World")
next.ServeHTTPC(ctx, w, r)
})
})(xh)
ctx := context.Background()
// Bridge context aware handlers with http.Handler using xhandler.Handle()
http.Handle("/", xhandler.New(ctx, xh))
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal(err)
}
}
func ExampleHandleTimeout() {
var xh xhandler.HandlerC
xh = xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello World"))
if _, ok := ctx.Deadline(); ok {
w.Write([]byte(" with deadline"))
}
})
// This handler adds a timeout to the handler
xh = xhandler.TimeoutHandler(5 * time.Second)(xh)
ctx := context.Background()
// Bridge context aware handlers with http.Handler using xhandler.Handle()
http.Handle("/", xhandler.New(ctx, xh))
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal(err)
}
}