-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmiddleware.go
More file actions
83 lines (79 loc) · 1.56 KB
/
middleware.go
File metadata and controls
83 lines (79 loc) · 1.56 KB
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
package ghttp
import (
"net/http"
"errors"
)
//
type MiddlewareMethod func(ctx *Context)
//
type Middlewares []*Middleware
func(ms Middlewares)Len() int{
return len(ms)
}
func(ms Middlewares)Less(i, j int) bool{
if ms[i].currentPath < ms[j].currentPath{
return false
}
return true
}
func(ms Middlewares)Swap(i, j int){
ms[i],ms[j] = ms[j],ms[i]
}
type Middleware struct {
*Router
currentPath string
middFunc MiddlewareMethod
}
//
func NewMiddleware(path string) (*Middleware,error){
if path[0] != '/' {
return nil,errors.New("path must begin with '/' in path '" + path + "'")
}
if path[len(path) -1] != '/'{
path += "/"
}
m := &Middleware{
currentPath:path,
}
//
m.Router = NewRouter()
m.Router.setOptimizationPath(m.optimizationPath)
return m,nil
}
//
func (m *Middleware) ServeHTTP(w *ResponseWriter, req *http.Request){
ctx := NewContext(w,req)
ctx.setNextServeHTTP(m.Router)
w.setContext(ctx)
m.middFunc(ctx)
}
//
func(m *Middleware) matchPath(path string) bool{
if len(path) > len(m.currentPath) && path[0:len(m.currentPath)] == m.currentPath{
return true;
}
return false;
}
//
func(m *Middleware) getCurrentPath(path string) string{
return m.currentPath
}
func(m *Middleware) setCurrentPath(path string){
m.currentPath = path
}
//
func(m *Middleware) RegisterFunc(f MiddlewareMethod){
m.middFunc = f
}
//
func(m *Middleware) LoadRouter(r *Router){
m.Router = r
m.Router.setOptimizationPath(m.optimizationPath)
}
//
func (m *Middleware) optimizationPath(path string) string{
if path[0] == '/' {
path = path[1:]
}
return m.currentPath + path
}