-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathrest_test.go
316 lines (277 loc) · 8.15 KB
/
rest_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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
package rest
import (
"bytes"
"fmt"
"github.com/stretchrcom/testify/assert"
"io/ioutil"
"net/http"
"testing"
)
type FullTest struct {
Service `prefix:"/test/" realm:"tester"`
Hello Processor `method:"GET" path:"/hello/([a-zA-Z0-9]+)"`
Print Processor `method:"POST" path:"/print/([0-9]+)"`
Error_ Processor `method:"GET" path:"/error" func:"ErrorFunc"`
Request Processor `method:"GET" path:"/request"`
NoReturn Processor `method:"POST" path:"/noreturn"`
a int
}
func (t FullTest) Hello_(guest string) string {
path, _ := t.Hello.Path(guest)
t.RedirectTo(path)
return "hello " + guest
}
func (t FullTest) Print_(id int, post string) string {
ret := fmt.Sprintf("id(%d) post: %s", id, post)
t.Header().Set("Type", "abcd")
path, _ := t.Hello.Path("guest")
t.Header().Set("Location", path)
t.WriteHeader(http.StatusCreated)
return ret
}
func (t FullTest) ErrorFunc() string {
t.Error(http.StatusInternalServerError, fmt.Errorf("error: %s", "no reason"))
return ""
}
func (t FullTest) Request_() string {
query := t.Service.Request().URL.Query()
header := t.Service.Request().Header
return query.Get("a") + header.Get("B")
}
func (t FullTest) NoReturn_() {}
func TestRestful(t *testing.T) {
test := new(FullTest)
handler, err := New(test)
if err != nil {
t.Fatalf("can't init test: %s", err)
}
if handler.Prefix() != "/test" {
t.Fatal("handler root invalid:", handler.Prefix())
}
{
r, err := http.NewRequest("GET", "http://127.0.0.1:12345/test/hello/restful", nil)
if err != nil {
t.Fatal(err)
}
resp, status, header := sendRequest(handler, r)
if status != http.StatusTemporaryRedirect {
t.Errorf("call hello/restful status not redirect: %d", status)
}
if header.Get("Location") != "/test/hello/restful" {
t.Errorf("call hello/restful location error: %s", header.Get("Location"))
}
if resp != "\"hello restful\"\n" {
t.Errorf("call hello/restful response error: [%s]", resp)
}
}
{
buf := bytes.NewBufferString(`"post content"`)
r, err := http.NewRequest("POST", "http://127.0.0.1:12345/test/print/123", buf)
if err != nil {
t.Fatal(err)
}
r.Header.Set("Content-Type", "application/json; charset=utf-8")
resp, status, header := sendRequest(handler, r)
if status != http.StatusCreated {
t.Errorf("call print/123 status not created: %d", status)
}
if header.Get("Content-Type") != "application/json; charset=utf-8" {
t.Errorf("call print/123 Content-Type error: %s", header.Get("Content-Type"))
}
if header.Get("Type") != "abcd" {
t.Errorf("call print/123 Type error: %s", header.Get("Type"))
}
if header.Get("Location") != "/test/hello/guest" {
t.Errorf("call print/123 location error: %s", header.Get("Location"))
}
if resp != "\"id(123) post: post content\"\n" {
t.Errorf("call print/123 response error: [%s]", resp)
}
}
{
r, err := http.NewRequest("GET", "http://127.0.0.1:12345/test/error", nil)
if err != nil {
t.Fatal(err)
}
resp, status, _ := sendRequest(handler, r)
if status != http.StatusInternalServerError {
t.Errorf("call error status not redirect: %d", status)
}
if resp != "error: no reason\n" {
t.Errorf("call error response error: [%s]", resp)
}
}
{
r, err := http.NewRequest("GET", "http://127.0.0.1:12345/test/request?a=123", nil)
if err != nil {
t.Fatal(err)
}
r.Header.Set("B", "abc")
resp, status, _ := sendRequest(handler, r)
if status != http.StatusOK {
t.Errorf("call error status not ok: %d", status)
}
if resp != "\"123abc\"\n" {
t.Errorf("call error response error: [%s]", resp)
}
}
{
r, err := http.NewRequest("POST", "http://127.0.0.1:12345/test/noreturn", nil)
if err != nil {
t.Fatal(err)
}
r.Header.Set("Content-Type", "application/xml; charset=gbk")
resp, status, _ := sendRequest(handler, r)
if status != http.StatusOK {
t.Errorf("call error status not ok: %d", status)
}
if resp != "" {
t.Errorf("call error response error: [%s]", resp)
}
}
}
type NoServiceTest struct{}
type ServiceNotFirstTest struct {
a int
Service
}
type NoHandlerService struct {
Service
Hello Processor
}
type HandlerNotMatchService struct {
Service
Hello Processor `path:"/hello/(.*?)"`
}
func (s HandlerNotMatchService) Hello_() {}
func TestServiceError(t *testing.T) {
var tests = []interface{}{
1,
new(NoServiceTest),
new(ServiceNotFirstTest),
new(NoHandlerService),
new(HandlerNotMatchService),
}
for i, test := range tests {
_, err := New(test)
if err == nil {
t.Errorf("test %d should error", i)
}
}
}
func TestGetContentType(t *testing.T) {
type Test struct {
contentType string
mime string
charset string
}
var tests = []Test{
{"", "", ""},
{"application/xml", "application/xml", ""},
{"application/xml; charset=gbk", "application/xml", "gbk"},
{"application/xml; other=abc; charset=gbk", "application/xml", "gbk"},
{"application/xml; other=abc", "application/xml", ""},
}
for i, test := range tests {
req, _ := http.NewRequest("GET", "http://127.0.0.1/", nil)
req.Header.Set("Content-Type", test.contentType)
mime, charset := getContentTypeFromRequset(req)
assert.Equal(t, mime, test.mime, fmt.Sprintf("test %d", i))
assert.Equal(t, charset, test.charset, fmt.Sprintf("test %d", i))
}
}
type FindProcessor struct{}
func (t FindProcessor) handler1() {}
func (t FindProcessor) handler2(a string) {}
func (t FindProcessor) handler3(b string, c int) {}
func respHelper(resp *http.Response, e error) (ret string, code int, header http.Header, err error) {
if e != nil {
err = e
return
}
defer resp.Body.Close()
code = resp.StatusCode
header = resp.Header
body, e := ioutil.ReadAll(resp.Body)
if e != nil {
panic(e)
}
ret = string(body)
return
}
type responseWriter struct {
status int
header http.Header
buf *bytes.Buffer
}
func newResponseWriter() *responseWriter {
return &responseWriter{
status: http.StatusOK,
header: make(http.Header),
buf: bytes.NewBuffer(nil),
}
}
func (w *responseWriter) Header() http.Header {
return w.header
}
func (w *responseWriter) Write(p []byte) (int, error) {
return w.buf.Write(p)
}
func (w *responseWriter) WriteHeader(status int) {
w.status = status
}
func sendRequest(handler http.Handler, r *http.Request) (ret string, code int, header http.Header) {
resp := newResponseWriter()
handler.ServeHTTP(resp, r)
return resp.buf.String(), resp.status, resp.header
}
type Conversation struct {
Id int
To string
Text string
}
type RESTService struct {
Service `prefix:"/prefix"`
Hello Processor `path:"/hello/(.*?)/to/(.*?)" method:"GET"`
PostConv Processor `path:"/conversation/to/(.*?)" func:"PostConversation" method:"POST"`
Conv Processor `path:"/conversation/([0-9]+)" func:"GetConversation" method:"GET"`
Watch Streaming `path:"/conversation/streaming" method:"GET"`
}
// call /hello/{host}/to/{guest} and get a string.
// parameters in url will pass to processor's function orderly.
func (s RESTService) Hello_(host, guest string) string {
return "hello from " + host + " to " + guest
}
// call /conversation/to/{people}, post a string as text and return a conversation object.
// the post content will unmarshal to the last parameter of processor.
// when save the conversation to db, send new conv to people through streaming api.
func (s RESTService) PostConversation(to, post string) Conversation {
conv := Conversation{
Id: 1,
To: to,
Text: post,
}
path, _ := s.Conv.Path(conv.Id)
s.RedirectTo(path)
s.Watch.Feed(to, conv)
return conv
}
// call /conversation/{id} and get the conversation object.
// rest will automatically convert id in url to int type. if convert failed, return bad request.
func (s RESTService) GetConversation(id int) Conversation {
return Conversation{
Id: 1,
To: "to",
Text: "post",
}
}
// call /conversation/streaming, create a long connection and get the conversation update ASAP.
// this function will be called when connecting to get a identity from request.
// when feeding streaming, all connection with same identity will send the data.
func (s RESTService) Watch_() string {
return s.Request().URL.Query().Get("user")
}
func ExampleRest() {
handler, _ := New(new(RESTService))
http.ListenAndServe("127.0.0.1:8080", handler)
}