forked from xs23933/web
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcore.go
461 lines (423 loc) · 10.8 KB
/
core.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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
package web
import (
"crypto/tls"
"fmt"
"io"
"log"
"net"
"os"
"os/exec"
"reflect"
"regexp"
"runtime"
"strconv"
"strings"
"time"
"github.com/valyala/fasthttp"
)
// idea from nodejs koa
// Options all options
type Options struct {
Prefork bool // multiple go processes listening on the some port
// ETag 发送etag
ETag bool
ServerName string
// Fasthttp options
Concurrency int // default: 256 * 1024
NoDefaultDate bool
DisableKeepalive bool
ReadTimeout time.Duration
WriteTimeout time.Duration
IdleTimeout time.Duration
MaxRequestBodySize int
Debug bool
ViewEngine ViewEngine
}
// Core core class
type Core struct {
*Options
*fasthttp.Server
routes []*Route
}
// Static struct
type Static struct {
Compress bool
ByteRange bool
Browse bool
Index string
}
// New new core
func New(opts ...*Options) *Core {
c := new(Core)
c.Options = new(Options)
if len(opts) == 1 {
c.Options = opts[0]
}
return c
}
// RegView 注册模版引擎
func (c *Core) RegView(viewEngine ViewEngine) {
c.ViewEngine = viewEngine
}
// View executes and writes the result of a template file to the writer.
//
// First parameter is the writer to write the parsed template.
// Second parameter is the relative, to templates directory, template filename, including extension.
// Third parameter is the layout, can be empty string.
// Forth parameter is the bindable data to the template, can be nil.
//
// Use context.View to render templates to the client instead.
// Returns an error on failure, otherwise nil.
func (c *Core) View(writer io.Writer, filename string, layout string, bind interface{}) error {
return c.ViewEngine.ExecuteWriter(writer, filename, layout, bind)
}
func (c *Core) regStatic(prefix, root string, config ...Static) {
if prefix == "" {
prefix = "/"
}
if prefix[0] != '/' && prefix[0] != '*' {
prefix = "/" + prefix
}
// Match anything
var wildcard = false
if prefix == "*" || prefix == "/*" {
wildcard = true
prefix = "/"
}
prefix = strings.ToLower(prefix)
// For security we want to restrict to the current work directory.
if len(root) == 0 {
root = "."
}
// Strip trailing slashes from the root path
if len(root) > 0 && root[len(root)-1] == '/' {
root = root[:len(root)-1]
}
// isSlash ?
var isSlash = prefix == "/"
if strings.Contains(prefix, "*") {
wildcard = true
prefix = strings.Split(prefix, "*")[0]
}
var stripper = len(prefix)
if isSlash {
stripper = 0
}
// Fileserver settings
fs := &fasthttp.FS{
Root: root,
GenerateIndexPages: false,
AcceptByteRange: false,
Compress: false,
CompressedFileSuffix: ".tar.gz",
CacheDuration: 10 * time.Second,
IndexNames: []string{"index.html"},
PathRewrite: fasthttp.NewPathPrefixStripper(stripper),
PathNotFound: func(ctx *fasthttp.RequestCtx) {
ctx.Response.SetStatusCode(404)
ctx.Response.SetBodyString("Not Found")
},
}
// Set config if provided
if len(config) > 0 {
fs.Compress = config[0].Compress
fs.AcceptByteRange = config[0].ByteRange
fs.GenerateIndexPages = config[0].Browse
if config[0].Index != "" {
fs.IndexNames = []string{config[0].Index}
}
}
fileHandler := fs.NewRequestHandler()
c.routes = append(c.routes, &Route{
isMiddleware: true,
isSlash: isSlash,
Method: "*",
Path: prefix,
Handler: func(ctx *Ctx) {
// Only handle GET & HEAD methods
if ctx.method == "GET" || ctx.method == "HEAD" {
// Do stuff
if wildcard {
ctx.Request.SetRequestURI(prefix)
}
// Serve file
fileHandler(ctx.RequestCtx)
// Finish request if found and not forbidden
status := ctx.Response.StatusCode()
if status != 404 && status != 403 {
return
}
// Reset response
ctx.Response.Reset()
}
ctx.Next()
},
})
}
// Static registers a new route with path prefix to serve static files from the provided root directory.
func (c *Core) Static(prefix, root string, config ...Static) *Core {
c.regStatic(prefix, root, config...)
return c
}
// Use registers a middleware route.
func (c *Core) Use(args ...interface{}) *Core {
path := ""
var handlers []func(*Ctx)
skip := false // 不需要综合注册
for i := 0; i < len(args); i++ {
switch arg := args[i].(type) {
case string:
path = arg
case func(*Ctx):
handlers = append(handlers, arg)
case handle:
skip = true
c.buildHands(arg)
default:
log.Fatalf("Use not support %v\n", arg)
}
}
if skip {
return c
}
c.pushMethod("USE", path, handlers...)
return c
}
func (c *Core) buildHands(hand handle) {
hand.Init()
// register routers
refCtl := reflect.TypeOf(hand)
methodCount := refCtl.NumMethod()
valFn := reflect.ValueOf(hand)
fmt.Println("+ ---- Auto register router ---- +")
prefix := hand.Prefix()
c.pushMethod("USE", prefix, hand.Preload)
for i := 0; i < methodCount; i++ {
m := refCtl.Method(i)
name := toNamer(m.Name)
switch {
case strings.HasPrefix(name, "get"):
if fn, ok := (valFn.Method(i).Interface()).(func(*Ctx)); ok {
name = fixURI(prefix, name, "get")
c.pushMethod("GET", name, fn)
fmt.Printf("| %s\t%s\n", Magenta("GET"), name)
}
case strings.HasPrefix(name, "post"):
if fn, ok := (valFn.Method(i).Interface()).(func(*Ctx)); ok {
name = fixURI(prefix, name, "post")
c.pushMethod("POST", name, fn)
fmt.Printf("| %s\t%s\n", Magenta("POST"), name)
}
case strings.HasPrefix(name, "put"):
if fn, ok := (valFn.Method(i).Interface()).(func(*Ctx)); ok {
name = fixURI(prefix, name, "put")
c.pushMethod("PUT", name, fn)
fmt.Printf("| %s\t%s\n", Magenta("PUT"), name)
}
case strings.HasPrefix(name, "delete"):
if fn, ok := (valFn.Method(i).Interface()).(func(*Ctx)); ok {
name = fixURI(prefix, name, "delete")
c.pushMethod("DELETE", name, fn)
fmt.Printf("| %s\t%s\n", Magenta("DELETE"), name)
}
case strings.HasPrefix(name, "all"):
if fn, ok := (valFn.Method(i).Interface()).(func(*Ctx)); ok {
name = fixURI(prefix, name, "all")
c.pushMethod("ALL", name, fn)
fmt.Printf("| %s\t%s\n", Magenta("ALL"), name)
}
}
}
fmt.Println("+ ------------------------------ +")
c.pushMethod("GET", "/check", func(ctx *Ctx) {
ctx.Send("ok")
})
}
func (c *Core) pushMethod(method, path string, handlers ...func(*Ctx)) {
if len(handlers) == 0 {
log.Fatalf("Missing handler in router")
}
if path == "" {
path = "/"
}
original := path
path = strings.ToLower(path)
if len(path) > 1 {
path = strings.TrimRight(path, "/")
}
var isGet = method == "GET"
var isMiddleware = method == "USE"
if isMiddleware || method == "ALL" {
method = "*"
}
var isStar = path == "*" || path == "/*"
if isMiddleware && path == "/" {
isStar = true
}
var isSlash = path == "/"
var isRegex = false
var Params = getParams(original)
var Regexp *regexp.Regexp
if len(Params) > 0 {
regex, err := getRegex(path)
if err != nil {
log.Fatalf("Router: invalid path pattern: %s", path)
}
isRegex = true
Regexp = regex
}
for i := range handlers {
c.routes = append(c.routes, &Route{
isGet: isGet,
isMiddleware: isMiddleware,
isStar: isStar,
isSlash: isSlash,
isRegex: isRegex,
Method: method,
Path: path,
Params: Params,
Regexp: Regexp,
Handler: handlers[i],
})
}
}
// Build Initialize
func (c *Core) Build() error {
c.Server = c.newServer()
if c.ViewEngine == nil {
for _, s := range []string{"./views", "./templates", "./web/views"} {
if _, err := os.Stat(s); os.IsNotExist(err) {
continue
}
c.RegView(Handlebars(s, ".html"))
break
}
}
if c.ViewEngine != nil {
if err := c.ViewEngine.Load(); err != nil {
log.Fatalf("View builder %v", err)
}
}
return nil
}
// Serve 启动
func (c *Core) Serve(address interface{}, tlsopt ...*tls.Config) error {
addr, ok := address.(string)
if !ok {
port, ok := address.(int)
if !ok {
return fmt.Errorf("serve: host must be an int port or string address")
}
addr = strconv.Itoa(port)
}
if !strings.Contains(addr, ":") {
addr = ":" + addr
}
if err := c.Build(); err != nil {
panic(err)
}
var ln net.Listener
var err error
if c.Prefork && runtime.NumCPU() > 1 && runtime.GOOS != "windows" {
if ln, err = c.prefork(addr); err != nil {
return err
}
} else {
if ln, err = net.Listen("tcp", addr); err != nil {
return err
}
}
if len(tlsopt) > 0 {
ln = tls.NewListener(ln, tlsopt[0])
}
fmt.Printf("Started server on %s\n", Cyan(ln.Addr().String()))
return c.Server.Serve(ln)
}
// Sharding: https://www.nginx.com/blog/socket-sharding-nginx-release-1-9-1/
func (c *Core) prefork(addr string) (ln net.Listener, err error) {
if !isChild() {
addr, err := net.ResolveTCPAddr("tcp", addr)
if err != nil {
return ln, err
}
tcplistener, err := net.ListenTCP("tcp", addr)
if err != nil {
return ln, err
}
fl, err := tcplistener.File()
if err != nil {
return ln, err
}
files := []*os.File{fl}
childs := make([]*exec.Cmd, runtime.NumCPU()/2)
for i := range childs {
childs[i] = exec.Command(os.Args[0], append(os.Args[1:], "-prefork", "-child")...)
childs[i].Stdout = os.Stdout
childs[i].Stderr = os.Stderr
childs[i].ExtraFiles = files
if err := childs[i].Start(); err != nil {
return ln, err
}
}
for k := range childs {
if err := childs[k].Wait(); err != nil {
return ln, err
}
}
os.Exit(0)
} else {
runtime.GOMAXPROCS(1)
ln, err = net.FileListener(os.NewFile(3, ""))
}
return
}
func (c *Core) handler(fctx *fasthttp.RequestCtx) {
ctx := acquireCtx(fctx)
defer releaseCtx(ctx)
ctx.Core = c
ctx.path = strings.ToLower(ctx.path)
if len(ctx.path) > 1 {
ctx.path = strings.TrimRight(ctx.path, "/")
}
start := time.Now()
c.nextRoute(ctx)
if c.Debug {
d := time.Now().Sub(start).String()
log.Printf("%s\t%s\t %d %s\n", Green(ctx.method), ctx.path, ctx.Response.StatusCode(), Yellow(d))
}
}
func (c *Core) nextRoute(ctx *Ctx) {
rlen := len(c.routes) - 1
for ctx.index < rlen {
ctx.index++
route := c.routes[ctx.index]
match, values := route.matchRoute(ctx.method, ctx.path)
if match {
ctx.Route = route
ctx.values = values
route.Handler(ctx)
if c.ETag {
setETag(ctx, ctx.Response.Body(), false)
}
return
}
}
if len(ctx.RequestCtx.Response.Body()) == 0 { // send a 404
ctx.SendStatus(404)
}
}
func (c *Core) newServer() *fasthttp.Server {
s := &fasthttp.Server{
Handler: c.handler,
Name: c.ServerName,
Concurrency: c.Options.Concurrency,
NoDefaultDate: c.Options.NoDefaultDate,
DisableKeepalive: c.Options.DisableKeepalive,
ReadTimeout: c.Options.ReadTimeout,
WriteTimeout: c.Options.WriteTimeout,
IdleTimeout: c.Options.IdleTimeout,
MaxRequestBodySize: c.Options.MaxRequestBodySize,
NoDefaultServerHeader: c.ServerName == "",
}
return s
}