-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcore.go
74 lines (65 loc) · 1.55 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
package conch
import (
"net/http"
"regexp"
"time"
)
type Router struct {
Pattern string
Func func(ctx Context)
}
type App struct {
Routers []Router
LogPath string
}
// 中间件
func (app App)middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
start := time.Now()
next.ServeHTTP(res, req)
app.Log("%s (%v)", req.URL.Path, time.Since(start))
})
}
// 路由处理
func (app App) handleRouter(res http.ResponseWriter, req *http.Request) {
isFound := false
for _, router := range app.Routers {
// 循环匹配,先添加的先匹配
reg, err := regexp.Compile(router.Pattern)
if err != nil {
continue
}
if reg.MatchString(req.URL.Path) {
isFound = true
router.Func(Context{
Response: res,
Request: req,
App: app,
})
}
}
if !isFound {
// 未匹配到路由
_, _ = res.Write([]byte("Url Not Found!"))
}
}
// 处理静态文件
func (app App) Static(pattern string, path string) {
http.Handle(pattern, http.StripPrefix(pattern, http.FileServer(http.Dir(path))))
}
// Handle
func (app App) Handle(pattern string, handle http.Handler) {
http.Handle(pattern, handle)
}
// 启动监听
func (app App) Run(addr string) {
http.Handle("/", app.middleware(http.HandlerFunc(app.handleRouter)))
app.Log("Server started: " + addr)
if err := http.ListenAndServe(addr, nil); err != nil {
app.Log("Http listened failed: %s", err.Error())
}
}
// 打印日志
func (app App) Log(format string, arg ...interface{}) {
Log{Path: app.LogPath}.Out(format, arg...)
}