-
Notifications
You must be signed in to change notification settings - Fork 0
/
httpserve_test.go
119 lines (97 loc) · 2.34 KB
/
httpserve_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
package httpserve
import (
"io/ioutil"
"net/http"
"testing"
"time"
)
func TestServeText(t *testing.T) {
var (
resp *http.Response
bs []byte
err error
)
textVal := "hello"
serve := New()
defer func() {
if err = serve.Close(); err != nil {
t.Fatal(err)
}
}()
// Create derp group
derp := serve.Group("/derp")
// Setup text resonse handler
derp.GET("hello", func(ctx *Context) Response {
return NewTextResponse(200, []byte(textVal))
})
// Listen within a new goroutine
go func() {
if err := serve.Listen(8080); err != nil && err != http.ErrServerClosed {
t.Fatal(err)
}
}()
// Sleep for 200 milliseconds to ensure we've given the serve instance enough time to listen
time.Sleep(200 * time.Millisecond)
// Perform GET request
if resp, err = http.Get("http://localhost:8080/derp/hello"); err != nil {
t.Fatal(err)
}
// Read body as bytes
if bs, err = ioutil.ReadAll(resp.Body); err != nil {
t.Fatal(err)
}
// Close response body
if err = resp.Body.Close(); err != nil {
t.Fatal(err)
}
// Ensure values are correct
if string(bs) != textVal {
t.Fatalf("invalid value, expected \"%s\" and received \"%s\"", string(bs), textVal)
}
}
func TestServeJSON(t *testing.T) {
var (
jsonVal TestJSONStruct
ts TestJSONStruct
resp *http.Response
err error
)
jsonVal.Name = "John Doe"
jsonVal.Age = 33
serve := New()
defer func() {
if err = serve.Close(); err != nil {
t.Fatal(err)
}
}()
// Create derp group
derp := serve.Group("/derp")
// Setup json response handler
derp.GET("world", func(ctx *Context) Response {
return NewJSONResponse(200, jsonVal)
})
// Listen within a new goroutine
go func() {
if err := serve.Listen(8080); err != nil && err != http.ErrServerClosed {
t.Fatal(err)
}
}()
// Sleep for 200 milliseconds to ensure we've given the serve instance enough time to listen
time.Sleep(200 * time.Millisecond)
// Perform GET request
if resp, err = http.Get("http://localhost:8080/derp/world"); err != nil {
t.Fatal(err)
}
// Decode response body as TestJSONStruct
if err = DecodeJSONValue(resp.Body, &ts); err != nil {
t.Fatal(err)
}
// Close response body
if err = resp.Body.Close(); err != nil {
t.Fatal(err)
}
// Ensure values are correct
if ts != jsonVal {
t.Fatalf("invalid value, expected \"%#v\" and received \"%#v\"", ts, jsonVal)
}
}