-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
311 lines (297 loc) · 7.17 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
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
package main
import (
"bytes"
"context"
"fmt"
xhttp "github.com/goclub/http"
"github.com/google/uuid"
"html/template"
"io/ioutil"
"log"
"net/http"
"time"
)
type traceID string
func main() {
router := NewRouter()
// request
RequestBindQuery(router)
RequestBindFormUrlencoded(router)
RequestBindFormData(router)
RequestBindJSON(router)
RequestBindQueryAndJSON(router)
RequestBindParam(router)
RenderFormFile(router)
RequestFile(router)
router.Use(func(c *xhttp.Context, next xhttp.Next) (err error) {
c.Request = c.Request.WithContext(context.WithValue(c.Request.Context(), traceID("traceID"), uuid.New().String()))
return next()
})
RequestTraceID(router)
// response
ResponseWriteBytes(router)
ResponseHTML(router)
ResponseTemplate(router)
GetSetCookie(router)
addr := ":3000"
serve := &http.Server{
Handler: router,
Addr: addr,
}
router.LogPatterns(serve)
go func() {
listenErr := serve.ListenAndServe()
if listenErr != nil {
if listenErr != http.ErrServerClosed {
panic(listenErr)
}
}
}()
xhttp.GracefulClose(func() {
log.Print("Shuting down server...")
if err := serve.Shutdown(context.Background()); err != nil {
log.Fatal("Server forced to shutdown:", err)
}
log.Println("Server exiting")
})
}
func NewRouter() *xhttp.Router {
router := xhttp.NewRouter(xhttp.RouterOption{})
return router
}
// 打开 http://127.0.0.1:3000/request/query?name=nimoc&age=18
func RequestBindQuery(router *xhttp.Router) {
route := xhttp.Route{
xhttp.GET, "/request/query",
}
router.HandleFunc(route, func(c *xhttp.Context) (err error) {
req := struct {
Name string `query:"name"`
Age int `query:"age"`
}{}
err = c.BindRequest(&req)
if err != nil {
return
}
dump := fmt.Sprintf("%+v", req)
return c.WriteBytes([]byte(dump))
})
}
func RequestBindFormUrlencoded(router *xhttp.Router) {
route := xhttp.Route{
xhttp.POST, "/request/form_urlencoded",
}
router.HandleFunc(route, func(c *xhttp.Context) (err error) {
req := struct {
Name string `form:"name"`
Age int `form:"age"`
}{}
err = c.BindRequest(&req)
if err != nil {
return
}
dump := fmt.Sprintf("%+v", req)
return c.WriteBytes([]byte(dump))
})
}
/*
使用 curl 发起请求
curl --location --request POST 'http://127.0.0.1:3000/request/form_data' \
--form 'name="nimoc"' \
--form 'age="18"'
*/
func RequestBindFormData(router *xhttp.Router) {
route := xhttp.Route{
xhttp.POST, "/request/form_data",
}
router.HandleFunc(route, func(c *xhttp.Context) (err error) {
req := struct {
Name string `form:"name"`
Age int `form:"age"`
}{}
err = c.BindRequest(&req)
if err != nil {
return
}
dump := fmt.Sprintf("%+v", req)
return c.WriteBytes([]byte(dump))
})
}
/*
使用 curl 发起请求
curl --location --request GET 'http://127.0.0.1:3000/request/json' \
--header 'Content-Type: application/json' \
--data-raw '{
"name":"nimoc",
"age": 18
}'
*/
func RequestBindJSON(router *xhttp.Router) {
route := xhttp.Route{
xhttp.GET, "/request/json",
}
router.HandleFunc(route, func(c *xhttp.Context) (err error) {
req := struct {
Name string `json:"name"`
Age int `json:"age"`
}{}
err = c.BindRequest(&req)
if err != nil {
return
}
dump := fmt.Sprintf("%+v", req)
return c.WriteBytes([]byte(dump))
})
}
/*
curl --location --request GET 'http://127.0.0.1:3000/request/query_and_json?id=11' \
--header 'Content-Type: application/json' \
--data-raw '{
"name":"nimoc",
"age": 18
}'
*/
func RequestBindQueryAndJSON(router *xhttp.Router) {
route := xhttp.Route{
xhttp.POST, "/request/query_and_json",
}
router.HandleFunc(route, func(c *xhttp.Context) (err error) {
req := struct {
ID string `query:"id"`
Name string `json:"name"`
Age int `json:"age"`
}{}
err = c.BindRequest(&req)
if err != nil {
return
}
dump := fmt.Sprintf("%+v", req)
return c.WriteBytes([]byte(dump))
})
}
// http://127.0.0.1:3000/request/param/11
func RequestBindParam(router *xhttp.Router) {
route := xhttp.Route{
xhttp.GET, "/request/param/{userID}",
}
router.HandleFunc(route, func(c *xhttp.Context) (err error) {
req := struct {
UserID string `param:"userID"`
}{}
err = c.BindRequest(&req)
if err != nil {
return
}
dump := fmt.Sprintf("%+v", req)
return c.WriteBytes([]byte(dump))
})
}
func RenderFormFile(router *xhttp.Router) {
route := xhttp.Route{
xhttp.GET, "/request/file",
}
router.HandleFunc(route, func(c *xhttp.Context) (err error) {
html := []byte(`
<form action="/request/file" method="post" enctype="multipart/form-data" >
<input type="file" name="file" /> <br />
<button type="submit" >上传</button>
</form>`)
return c.Render(func(buffer *bytes.Buffer) error {
buffer.Write(html)
return nil
})
})
}
// 打开 http://127.0.0.1:3000/request/file 上传文件
func RequestFile(router *xhttp.Router) {
route := xhttp.Route{
xhttp.POST, "/request/file",
}
router.HandleFunc(route, func(c *xhttp.Context) (err error) {
file, fileHeader, err := c.Request.FormFile("file")
if err != nil {
return
}
defer file.Close()
data, err := ioutil.ReadAll(file)
if err != nil {
return
}
body := append([]byte(fileHeader.Filename+":"), data...)
return c.WriteBytes(body)
})
}
func RequestTraceID(router *xhttp.Router) {
route := xhttp.Route{
xhttp.GET, "/request/trace_id",
}
router.HandleFunc(route, func(c *xhttp.Context) (err error) {
return c.WriteBytes([]byte(fmt.Sprintf("traceID: %s", c.Request.Context().Value(traceID("traceID")))))
})
}
func ResponseWriteBytes(router *xhttp.Router) {
route := xhttp.Route{
xhttp.GET, "/response/WriteBytes",
}
router.HandleFunc(route, func(c *xhttp.Context) (err error) {
return c.WriteBytes([]byte("goclub"))
})
}
func ResponseHTML(router *xhttp.Router) {
route := xhttp.Route{
xhttp.GET, "/response/html",
}
router.HandleFunc(route, func(c *xhttp.Context) (err error) {
return c.Render(func(buffer *bytes.Buffer) error {
buffer.WriteString(`<a href="http://github.com/goclub">goclub</a>`)
return nil
})
})
}
var responseTPL = template.Must(template.New("").Parse("name {{.Name}}"))
func ResponseTemplate(router *xhttp.Router) {
route := xhttp.Route{
xhttp.GET, "/response/template",
}
router.HandleFunc(route, func(c *xhttp.Context) (err error) {
return c.Render(func(buffer *bytes.Buffer) error {
data := struct {
Name string
}{Name: "nimoc"}
return responseTPL.Execute(buffer, data)
})
})
}
func GetSetCookie(router *xhttp.Router) {
router.HandleFunc(xhttp.Route{xhttp.GET, "/cookie"}, func(c *xhttp.Context) (err error) {
query := c.Request.URL.Query()
switch query.Get("kind") {
case "get":
var nameCookie *http.Cookie
var hasValue bool
nameCookie, hasValue, err = c.Cookie("name")
if err != nil {
return
}
var name string
if !hasValue {
name = ""
} else {
name = nameCookie.Value
}
return c.WriteBytes([]byte("name:" + name))
case "set":
name := query.Get("name")
if name == "" {
name = time.Now().String()
}
c.SetCookie(&http.Cookie{
Name: "name",
Value: name,
})
return c.WriteBytes([]byte("set cookie done"))
default:
return c.WriteBytes([]byte("kind query.must be get or set"))
}
})
}