-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathapp.go
219 lines (193 loc) · 4.7 KB
/
app.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
package GoInk
import (
"fmt"
"net/http"
"runtime/debug"
"strings"
)
// App struct is top level application.
// It contains Router,View,Config and private fields.
type App struct {
router *Router
routerC map[string]*routerCache
view *View
middle []Handler
inter map[string]Handler
config *Config
}
// New creates an App instance.
// It loads config.json file if exist.
// Otherwise, set default config values to Config.
func New() *App {
a := new(App)
a.router = NewRouter()
a.routerC = make(map[string]*routerCache)
a.middle = make([]Handler, 0)
a.inter = make(map[string]Handler)
a.config, _ = NewConfig("config.json")
a.view = NewView(a.config.StringOr("app.view_dir", "view"))
return a
}
// Use adds middleware handlers.
// Middleware handlers invoke before route handler in the order that they are added.
func (app *App) Use(h ...Handler) {
app.middle = append(app.middle, h...)
}
// Config returns global *Config instance.
func (app *App) Config() *Config {
return app.config
}
// View returns global *View instance.
func (app *App) View() *View {
return app.view
}
func (app *App) handler(res http.ResponseWriter, req *http.Request) {
context := NewContext(app, res, req)
defer func() {
e := recover()
if e == nil {
context = nil
return
}
context.Body = []byte(fmt.Sprint(e))
context.Status = 503
println(string(context.Body))
debug.PrintStack()
if _, ok := app.inter["recover"]; ok {
app.inter["recover"](context)
}
if !context.IsEnd {
context.End()
}
context = nil
}()
if _, ok := app.inter["static"]; ok {
app.inter["static"](context)
if context.IsEnd {
return
}
}
if len(app.middle) > 0 {
for _, h := range app.middle {
h(context)
if context.IsEnd {
break
}
}
}
if context.IsSend {
return
}
var (
params map[string]string
fn []Handler
url = req.URL.Path
)
if _, ok := app.routerC[url]; ok {
params = app.routerC[url].param
fn = app.routerC[url].fn
} else {
params, fn = app.router.Find(url, req.Method)
}
if params != nil && fn != nil {
context.routeParams = params
rc := new(routerCache)
rc.param = params
rc.fn = fn
app.routerC[url] = rc
for _, f := range fn {
f(context)
if context.IsEnd {
break
}
}
if !context.IsEnd {
context.End()
}
} else {
println("router is missing at " + req.URL.Path)
context.Status = 404
if _, ok := app.inter["notfound"]; ok {
app.inter["notfound"](context)
if !context.IsEnd {
context.End()
}
} else {
context.Throw(404)
}
}
context = nil
}
// ServeHTTP is HTTP server implement method. It makes App compatible to native http handler.
func (app *App) ServeHTTP(res http.ResponseWriter, req *http.Request) {
app.handler(res, req)
}
// Run http server and listen on config value or 9001 by default.
func (app *App) Run() {
addr := app.config.StringOr("app.server", "localhost:9001")
println("http server run at " + addr)
e := http.ListenAndServe(addr, app)
panic(e)
}
// Set app config value.
func (app *App) Set(key string, v interface{}) {
app.config.Set("app."+key, v)
}
// Get app config value if only key string given, return string value.
// If fn slice given, register GET handlers to router with pattern string.
func (app *App) Get(key string, fn ...Handler) string {
if len(fn) > 0 {
app.router.Get(key, fn...)
return ""
}
return app.config.String("app." + key)
}
// Register POST handlers to router.
func (app *App) Post(key string, fn ...Handler) {
app.router.Post(key, fn...)
}
// Register PUT handlers to router.
func (app *App) Put(key string, fn ...Handler) {
app.router.Put(key, fn...)
}
// Register DELETE handlers to router.
func (app *App) Delete(key string, fn ...Handler) {
app.router.Delete(key, fn...)
}
// Register handlers to router with custom methods and pattern string.
// Support GET,POST,PUT and DELETE methods.
// Usage:
// app.Route("GET,POST","/test",handler)
//
func (app *App) Route(method string, key string, fn ...Handler) {
methods := strings.Split(method, ",")
for _, m := range methods {
switch m {
case "GET":
app.Get(key, fn...)
case "POST":
app.Post(key, fn...)
case "PUT":
app.Put(key, fn...)
case "DELETE":
app.Delete(key, fn...)
default:
println("unknow route method " + m)
}
}
}
// Register static file handler.
// It's invoked before route handler after middleware handler.
func (app *App) Static(h Handler) {
app.inter["static"] = h
}
// Register panic recover handler.
// It's invoked when panic error in middleware and route handlers.
func (app *App) Recover(h Handler) {
app.inter["recover"] = h
}
// Register NotFound handler.
// It's invoked after calling route handler but not matched.
func (app *App) NotFound(h Handler) {
app.inter["notfound"] = h
}