-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrouter.go
More file actions
90 lines (76 loc) · 1.82 KB
/
Copy pathrouter.go
File metadata and controls
90 lines (76 loc) · 1.82 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
83
84
85
86
87
88
89
90
// router.go
package flint
import (
"net/http"
"strings"
)
type HandlerFunc func(ctx *Context)
type Router struct {
routes map[string]map[string]HandlerFunc // method -> path -> handler
notFound HandlerFunc
}
func NewRouter() *Router {
return &Router{
routes: make(map[string]map[string]HandlerFunc),
notFound: nil,
}
}
// Tüm methodlar için
func (r *Router) Handle(method, path string, handler HandlerFunc) {
if r.routes[method] == nil {
r.routes[method] = make(map[string]HandlerFunc)
}
r.routes[method][path] = handler
}
// stdlib uyumu: ServeHTTP
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
methodHandlers, ok := r.routes[req.Method]
if !ok {
if r.notFound != nil {
ctx := &Context{Writer: w, Request: req}
r.notFound(ctx)
return
}
http.NotFound(w, req)
return
}
// statik veya parametreli kontrol
for path, handler := range methodHandlers {
params := make(map[string]string)
if matchPath(path, req.URL.Path, params) {
ctx := &Context{Writer: w, Request: req, Params: params}
handler(ctx)
return
}
}
if r.notFound != nil {
ctx := &Context{Writer: w, Request: req}
r.notFound(ctx)
return
}
http.NotFound(w, req)
}
// path ile request path eşleşiyor mu, parametreleri doldur
func matchPath(routePath, reqPath string, params map[string]string) bool {
routeParts := splitPath(routePath)
reqParts := splitPath(reqPath)
if len(routeParts) != len(reqParts) {
return false
}
for i := range routeParts {
if len(routeParts[i]) > 0 && routeParts[i][0] == ':' {
// parametreyi al
params[routeParts[i][1:]] = reqParts[i]
} else if routeParts[i] != reqParts[i] {
return false
}
}
return true
}
func splitPath(path string) []string {
path = strings.Trim(path, "/")
if path == "" {
return []string{}
}
return strings.Split(path, "/")
}