-
Notifications
You must be signed in to change notification settings - Fork 3
/
chain_example_test.go
111 lines (86 loc) · 2.33 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package chain_test
import (
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"github.com/codemodus/chain/v2"
)
func Example() {
// Nested handlers write either "0" or "1" to the response body before
// and after ServeHTTP() is called.
//
// endHandler writes "_END_" to the response body.
ch := chain.New(nestedHandler0, nestedHandler1)
ch = ch.Append(nestedHandler0)
mux := http.NewServeMux()
mux.Handle("/010_End", ch.EndFn(endHandler))
server := httptest.NewServer(mux)
resp, err := respBody(server.URL + "/010_End")
if err != nil {
fmt.Println(err)
}
fmt.Println("Chain 010 Resp:", resp)
// Output:
// Chain 010 Resp: 010_END_010
}
func Example_advanced() {
// Nested handlers write either "0" or "1" to the response body before
// and after ServeHTTP() is called.
//
// endHandler writes "_END_" to the response body.
ch00 := chain.New(nestedHandler0, nestedHandler0)
ch001 := ch00.Append(nestedHandler1)
ch1 := chain.New(nestedHandler1)
ch1001 := ch1.Merge(ch001)
mux := http.NewServeMux()
mux.Handle("/00_End", ch00.EndFn(endHandler))
mux.Handle("/001_End", ch001.EndFn(endHandler))
mux.Handle("/1001_End", ch1001.EndFn(endHandler))
server := httptest.NewServer(mux)
resp00, err := respBody(server.URL + "/00_End")
if err != nil {
fmt.Println(err)
}
resp001, err := respBody(server.URL + "/001_End")
if err != nil {
fmt.Println(err)
}
resp1001, err := respBody(server.URL + "/1001_End")
if err != nil {
fmt.Println(err)
}
fmt.Println("Chain 00 Resp:", resp00)
fmt.Println("Chain 001 Resp:", resp001)
fmt.Println("Chain 1001 Resp:", resp1001)
// Output:
// Chain 00 Resp: 00_END_00
// Chain 001 Resp: 001_END_100
// Chain 1001 Resp: 1001_END_1001
}
func respBody(url string) (string, error) {
resp, err := http.Get(url)
if err != nil {
return "", err
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
_ = resp.Body.Close()
return string(body), nil
}
func nestedHandler0(n http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte(b0))
n.ServeHTTP(w, r)
_, _ = w.Write([]byte(b0))
})
}
func nestedHandler1(n http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte(b1))
n.ServeHTTP(w, r)
_, _ = w.Write([]byte(b1))
})
}