-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmain.go
132 lines (108 loc) · 2.44 KB
/
main.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
package main
import (
"bytes"
"fmt"
"net/http"
"runtime"
"strings"
"testing"
)
var (
httpHandlers map[string]http.Handler
)
func registerHandler(name string, handler http.Handler) {
if httpHandlers == nil {
httpHandlers = make(map[string]http.Handler)
} else if _, ok := httpHandlers[name]; ok {
panic("already registered")
}
httpHandlers[name] = handler
}
func getHandler(name string) http.Handler {
if httpHandlers == nil {
return nil
}
handler, _ := httpHandlers[name]
return handler
}
type mockResponseWriter struct {
}
func (m *mockResponseWriter) Header() http.Header {
return http.Header{}
}
func (m *mockResponseWriter) Write(p []byte) (int, error) {
return len(p), nil
}
func (m *mockResponseWriter) WriteHeader(code int) {
}
type simpleResponseWriter struct {
code int
body bytes.Buffer
header http.Header
}
func (m *simpleResponseWriter) Header() http.Header {
return m.header
}
func (m *simpleResponseWriter) Write(p []byte) (int, error) {
return m.body.Write(p)
}
func (m *simpleResponseWriter) WriteHeader(code int) {
m.code = code
}
func calcMem(name string, load func()) {
m := new(runtime.MemStats)
// before
runtime.GC()
runtime.ReadMemStats(m)
before := m.HeapAlloc
load()
// after
runtime.GC()
runtime.ReadMemStats(m)
after := m.HeapAlloc
println(" "+name+":", after-before, "Bytes")
}
func benchRequest(b *testing.B, router http.Handler, r *http.Request) {
w := mockResponseWriter{}
u := r.URL
r.RequestURI = u.RequestURI()
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
router.ServeHTTP(&w, r)
// clear caches
r.Form = nil
r.PostForm = nil
r.MultipartForm = nil
}
}
func sendRequest(router http.Handler, r *http.Request) (int, []byte, http.Header) {
w := simpleResponseWriter{header: http.Header{}}
router.ServeHTTP(&w, r)
return w.code, w.body.Bytes(), w.header
}
func testRequestWithPathParam(t *testing.T, handler http.Handler) {
req, _ := http.NewRequest("GET", "/gopher?name=gopher", nil)
c, b, h := sendRequest(handler, req)
if c != 0 && c != 200 {
t.Errorf("invalid status code: %d", c)
}
if !strings.Contains(string(b), "gopher") {
t.Errorf("invalid body: %s", string(b))
}
if h == nil {
t.Errorf("invalid header")
} else {
ct := h["Content-Type"]
if len(ct) <= 0 {
t.Errorf("invalid header")
} else {
if !strings.Contains(ct[0], "text/plain") {
t.Errorf("invalid header")
}
}
}
}
func main() {
fmt.Println("run: go test -bench=.")
}