-
Notifications
You must be signed in to change notification settings - Fork 0
/
middle_test.go
105 lines (85 loc) · 2.21 KB
/
middle_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
package greq_test
import (
"bytes"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"github.com/gookit/goutil/dump"
"github.com/gookit/goutil/netutil/httpreq"
"github.com/gookit/goutil/testutil/assert"
"github.com/gookit/greq"
)
type mid1 struct {
}
func (m mid1) Handle(r *http.Request, next greq.HandleFunc) (*greq.Response, error) {
dump.P("MID1++")
w, err := next(r)
dump.P("MID1--")
return w, err
}
func TestHReq_Use_Middleware(t *testing.T) {
buf := &bytes.Buffer{}
mid2 := func(r *http.Request, next greq.HandleFunc) (*greq.Response, error) {
dump.P("MID2++")
w, err := next(r)
dump.P("MID2--")
return w, err
}
resp, err := greq.New(testBaseURL).
Doer(testDoer).
Uses(&mid1{}, greq.MiddleFunc(mid2)).
GetDo("/get")
assert.NoErr(t, err)
assert.True(t, resp.IsOK())
err = resp.Write(buf)
assert.NoErr(t, err)
dump.P(buf.String())
}
func TestHReq_Use_MiddleFunc(t *testing.T) {
mid0 := greq.MiddleFunc(func(r *http.Request, next greq.HandleFunc) (*greq.Response, error) {
dump.P("MID0++")
w, err := next(r)
dump.P("MID0--")
return w, err
})
resp, err := greq.New(testBaseURL).
Doer(testDoer).
Middleware(mid0).
PutDo("/get")
assert.NoErr(t, err)
sc := resp.StatusCode
assert.True(t, httpreq.IsOK(sc))
}
func TestHReq_Use_Multi_MiddleFunc(t *testing.T) {
buf := &bytes.Buffer{}
mid0 := greq.MiddleFunc(func(r *http.Request, next greq.HandleFunc) (*greq.Response, error) {
buf.WriteString("MID0>>")
w, err := next(r)
buf.WriteString(">>MID0")
return w, err
})
mid1 := greq.MiddleFunc(func(r *http.Request, next greq.HandleFunc) (*greq.Response, error) {
buf.WriteString("MID1>>")
w, err := next(r)
buf.WriteString(">>MID1")
return w, err
})
mid2 := greq.MiddleFunc(func(r *http.Request, next greq.HandleFunc) (*greq.Response, error) {
buf.WriteString("MID2>>")
w, err := next(r)
buf.WriteString(">>MID2")
return w, err
})
resp, err := greq.New(testBaseURL).
Doer(httpreq.DoerFunc(func(req *http.Request) (*http.Response, error) {
tw := httptest.NewRecorder()
buf.WriteString("(CORE)")
return tw.Result(), nil
})).
Middleware(mid0, mid1, mid2).
PatchDo("/get")
assert.NoErr(t, err)
assert.True(t, resp.IsOK())
fmt.Println(buf.String())
}