generated from mythrnr/template-lib-golang
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample_test.go
88 lines (81 loc) · 2.26 KB
/
example_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
package group_test
import (
"fmt"
"log"
"net/http"
"github.com/julienschmidt/httprouter"
group "github.com/mythrnr/httprouter-group"
)
//nolint:testableexamples
func Example() {
// first, define routes, handlers, and middlewares.
g := group.New("/").GET(
func(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
w.Write([]byte("GET /\n"))
},
).Middleware(
func(h httprouter.Handle) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
w.Write([]byte("Middleware 1: before\n"))
h(w, r, p)
w.Write([]byte("Middleware 1: after\n"))
}
},
).Children(
group.New("/users").GET(
func(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
w.Write([]byte("GET /users\n"))
},
).Middleware(
func(h httprouter.Handle) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
w.Write([]byte("Middleware 2: before\n"))
h(w, r, p)
w.Write([]byte("Middleware 2: after\n"))
}
},
).Children(
group.New("/:id").GET(
func(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
w.Write([]byte("GET /users/:id\n"))
},
),
),
group.New("/users/:id").PUT(
func(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
w.Write([]byte("PUT /users/:id\n"))
},
).DELETE(
func(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
w.Write([]byte("DELETE /users/:id\n"))
},
).Middleware(
func(h httprouter.Handle) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
w.Write([]byte("Middleware 3: before\n"))
h(w, r, p)
w.Write([]byte("Middleware 3: after\n"))
}
},
),
)
// next, set up and configure router.
router := httprouter.New()
router.PanicHandler = func(_ http.ResponseWriter, _ *http.Request, rec interface{}) {
log.Fatal(rec)
}
// logging.
//
// GET /
// GET /users
// DELETE /users/:id
// GET /users/:id
// PUT /users/:id
fmt.Println(g.Routes().String())
// finally, register routes to httprouter instance.
// for _, r := range g.Routes() {
// router.Handle(r.Method(), r.Path(), r.Handler())
// }
// serve.
// log.Fatal(http.ListenAndServe(":8080", router))
}