-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrouter.go
179 lines (160 loc) · 4.13 KB
/
router.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
package h2o
import (
"context"
"fmt"
"net/http"
"os"
"os/signal"
"time"
log "github.com/Sirupsen/logrus"
"github.com/go-playground/form"
"github.com/gorilla/mux"
"github.com/rs/cors"
"github.com/unrolled/render"
validator "gopkg.in/go-playground/validator.v9"
)
// HandlerFunc an adapter to allow the use of ordinary functions as HTTP handler
type HandlerFunc func(*Context) error
// New new blank Engine instance without any middleware attached.
func New() *Router {
return &Router{
handlers: make([]HandlerFunc, 0),
routes: make([]*route, 0),
}
}
// Router associated with a prefix and an array of handlers
type Router struct {
path string
handlers []HandlerFunc
routes []*route
}
// Use use middlewares
func (p *Router) Use(handlers ...HandlerFunc) {
p.handlers = append(p.handlers, handlers...)
}
// Crud crud
func (p *Router) Crud(path string, list []HandlerFunc, create []HandlerFunc, read []HandlerFunc, update []HandlerFunc, delete []HandlerFunc) {
if list != nil {
p.GET(path, list...)
}
if create != nil {
p.POST(path, create...)
}
child := path + "/{id}"
if read != nil {
p.GET(child, read...)
}
if update != nil {
p.POST(child, update...)
}
if delete != nil {
p.DELETE(child, delete...)
}
}
// Group creates a new router group
func (p *Router) Group(group func(*Router), path string, handlers ...HandlerFunc) {
rt := &Router{
path: p.path + path,
handlers: append(p.handlers, handlers...),
routes: make([]*route, 0),
}
group(rt)
p.routes = append(p.routes, rt.routes...)
}
// GET http get
func (p *Router) GET(path string, handlers ...HandlerFunc) {
p.Handle(http.MethodGet, path, handlers...)
}
// POST http post
func (p *Router) POST(path string, handlers ...HandlerFunc) {
p.Handle(http.MethodPost, path, handlers...)
}
// PUT http put
func (p *Router) PUT(path string, handlers ...HandlerFunc) {
p.Handle(http.MethodPut, path, handlers...)
}
// PATCH http patch
func (p *Router) PATCH(path string, handlers ...HandlerFunc) {
p.Handle(http.MethodPatch, path, handlers...)
}
// DELETE http delete
func (p *Router) DELETE(path string, handlers ...HandlerFunc) {
p.Handle(http.MethodDelete, path, handlers...)
}
// Handle registers a new request handle and middleware with the given path and method.
func (p *Router) Handle(method, path string, handlers ...HandlerFunc) {
p.routes = append(
p.routes,
&route{
method: method,
path: p.path + path,
handlers: append(p.handlers, handlers...),
},
)
}
// Run attaches the router to a http.Server and starts listening and serving HTTP requests.
func (p *Router) Run(port int, grace bool, cro cors.Options, rdo render.Options) error {
addr := fmt.Sprintf(":%d", port)
log.Infof(
"application starting on http://localhost:%d",
port,
)
// --------------
rt := mux.NewRouter()
va := validator.New()
de := form.NewDecoder()
rd := render.New(rdo)
for _, r := range p.routes {
rt.HandleFunc(
r.path,
r.handle(func(w http.ResponseWriter, r *http.Request) *Context {
return &Context{
Request: r,
Writer: w,
vars: mux.Vars(r),
dec: de,
val: va,
rdr: rd,
}
}),
).Methods(r.method)
}
// ----------------
hnd := cors.New(cro).Handler(rt)
// ----------------
if grace {
srv := &http.Server{Addr: addr, Handler: hnd}
go func() {
// service connections
if err := srv.ListenAndServe(); err != nil {
log.Error(err)
}
}()
// Wait for interrupt signal to gracefully shutdown the server with
// a timeout of 5 seconds.
quit := make(chan os.Signal)
signal.Notify(quit, os.Interrupt)
<-quit
log.Warningf("shutdown server ...")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
return err
}
log.Info("server exist")
return nil
}
// ----------------
return http.ListenAndServe(addr, hnd)
}
// WalkFunc walk func
type WalkFunc func(method string, path string, handlers ...HandlerFunc) error
// Walk walk routes
func (p *Router) Walk(f WalkFunc) error {
for _, r := range p.routes {
if e := f(r.method, r.path, r.handlers...); e != nil {
return e
}
}
return nil
}