-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_test.go
88 lines (72 loc) · 2.1 KB
/
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
87
88
package xhttp_test
import (
"context"
"fmt"
"log"
"net/http"
"net/http/httptest"
"github.com/atdiar/xhttp"
)
const (
A = "A rainbow "
B = "Be very "
C = "Colorful "
)
func Example() {
s := xhttp.NewServeMux()
m := xhttp.Chain(middlewareExample{A, nil}, middlewareExample{B, nil}, middlewareExample{C, nil})
s.USE(m)
s.GET("/go/14", xhttp.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
a := req.Context().Value(A)
if a == nil {
fmt.Fprint(res, "Couldn't find a value in the context object for A") // shall make the test fail
}
fmt.Fprint(res, a)
b := req.Context().Value(B)
if b == nil {
fmt.Fprint(res, "Couldn't find a value in the context object for B") // shall make the test fail
}
fmt.Fprint(res, b)
c := req.Context().Value(C)
if c == nil {
fmt.Fprint(res, "Couldn't find a value in the context object for C") // shall make the test fail
}
fmt.Fprint(res, c)
}))
s.GET("/test", xhttp.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "test")
}))
s.GET("/test/3564", xhttp.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "ok")
}))
s.POST("/test/3564", xhttp.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "this is a post request")
}))
req, err := http.NewRequest("GET", "http://example.com/go/14", nil)
if err != nil {
log.Fatal(err)
}
w := httptest.NewRecorder()
s.ServeHTTP(w, req)
fmt.Printf("%d - %s", w.Code, w.Body.String())
// Output: 200 - OK OK OK A rainbow Be very Colorful
}
// Let's create a catchAll Handler i.e. an object implementing HandlerLinker.
// It's also what people may call a catchall middleware.
// This should illustrate one of the form a HandlerLinker can take.
type middlewareExample struct {
string
next xhttp.Handler
}
func (m middlewareExample) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "OK ")
c := context.WithValue(r.Context(), m.string, m.string)
r = r.WithContext(c)
if m.next != nil {
m.next.ServeHTTP(w, r)
}
}
func (m middlewareExample) Link(h xhttp.Handler) xhttp.HandlerLinker {
m.next = h
return m
}