-
Notifications
You must be signed in to change notification settings - Fork 0
/
routehandler.go
72 lines (64 loc) · 1.51 KB
/
routehandler.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
package mano
import (
"errors"
"fmt"
"net/http"
"strings"
)
type RouteHandler struct {
app *Application
prefix []string
}
func (handler *RouteHandler) Init(app *Application) error {
handler.app = app
return nil
}
func (handler *RouteHandler) Handle(writer http.ResponseWriter, request *http.Request) (complated bool, err error) {
defer func() {
if r := recover(); r != nil {
var ok bool
if err, ok = r.(error); !ok {
err = errors.New(fmt.Sprint(r))
}
}
}()
complated = true
routeData, matched := handler.app.routeTable.Match(ParseHttpMethod(request.Method), request.URL)
if !matched {
complated = false
return
}
ctx := newRequestContext(handler.app, request, writer, routeData)
// 中间件链
ch := &middlewareChan{
app: handler.app,
handler: routeData.entry.handler,
index: 0,
middlewares: routeData.entry.middlewares,
}
ctx.Data("lang", handler.app.lang) //设置默认语言资源到上下文
result := ch.exec(ctx)
view, ok := result.(View)
if ok {
} else if s, ok := result.(string); ok {
if strings.HasPrefix(s, "view:") {
view = ctx.View(s[5:])
} else {
view = ctx.Content(s)
}
} else {
panic(fmt.Errorf("unsupport returns value: %+v ", result))
}
contentType := view.ContentType()
if contentType == "" {
contentType = "application/octet-stream; charset=UTF-8"
}
writer.Header().Set("Content-Type", contentType)
view.Render(ctx)
return
}
func URLRouting(prefix ...string) *RouteHandler {
return &RouteHandler{
prefix: prefix,
}
}