-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinterceptor_http_test.go
More file actions
77 lines (69 loc) · 1.9 KB
/
interceptor_http_test.go
File metadata and controls
77 lines (69 loc) · 1.9 KB
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
package interceptor
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"net/http/httptest"
"testing"
)
func FooHttpInterceptor(rw http.ResponseWriter, req *http.Request, handler http.HandlerFunc) http.HandlerFunc {
return func(rw http.ResponseWriter, req *http.Request) {
log.Println("FooHttpInterceptor", req.RequestURI)
fmt.Fprint(rw, "foo")
handler(rw, req)
}
}
func BarHttpInterceptor(rw http.ResponseWriter, req *http.Request, handler http.HandlerFunc) http.HandlerFunc {
return func(rw http.ResponseWriter, req *http.Request) {
log.Println("BarHttpInterceptor", req.RequestURI)
fmt.Fprint(rw, "bar")
handler(rw, req)
}
}
func ForbiddenHttpInterceptor(rw http.ResponseWriter, req *http.Request, handler http.HandlerFunc) http.HandlerFunc {
return func(rw http.ResponseWriter, req *http.Request) {
log.Println("ForbiddenHttpInterceptor", req.RequestURI)
rw.WriteHeader(http.StatusForbidden)
fmt.Fprint(rw, "forbidden")
return
handler(rw, req)
}
}
func TestChainHttpInterceptor(t *testing.T) {
helloHandler := func(rw http.ResponseWriter, req *http.Request) {
fmt.Fprint(rw, `helloworld!`)
}
testcases := []struct {
warp func(http.HandlerFunc) http.HandlerFunc
want string
}{
{
warp: HttpInterceptorWarp(FooHttpInterceptor, BarHttpInterceptor),
want: "foobarhelloworld!",
},
{
// 设置Header 需要在write之前,foo会写body,故把forbidden放在前面
warp: HttpInterceptorWarp(ForbiddenHttpInterceptor, FooHttpInterceptor),
want: "forbidden",
},
}
for _, it := range testcases {
ts := httptest.NewServer(it.warp(helloHandler))
resp, err := http.Get(ts.URL)
if err != nil {
log.Fatal(err)
}
greeting, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Errorf("err: %+v", err)
}
ts.Close()
resp.Body.Close()
got := string(greeting)
fmt.Printf("resp: %s\n", got)
if got != it.want {
t.Errorf("got: %s want: %s", got, it.want)
}
}
}