diff options
| author | Eltrac <hi@guhub.cn> | 2025-11-26 09:54:49 +0800 |
|---|---|---|
| committer | Eltrac <hi@guhub.cn> | 2025-11-26 09:54:49 +0800 |
| commit | a555355d69a4fe9cd01d8bea86ce5b057cd1cd66 (patch) | |
| tree | ab3a4efaf52f88f5c72eda9e961407e77a60ba2f /router.go | |
| parent | 2f572636121a78c51b7188b7bd09965cb91c9dde (diff) | |
feat: implement minimal router
Diffstat (limited to 'router.go')
| -rw-r--r-- | router.go | 59 |
1 files changed, 59 insertions, 0 deletions
@@ -1 +1,60 @@ package growel + +import ( + "strings" +) + +type route struct { + method string + parts []string + handler Handler +} + +type Router struct { + routes []route +} + +func NewRouter() *Router { + return &Router{} +} + +func (r *Router) Add(method, path string, h Handler) { + parts := strings.Split(path, "/") + r.routes = append(r.routes, route{method, parts, h}) +} + +func (r *Router) Find(method, path string) (Handler, map[string]string) { + parts := strings.Split(path, "/") + + for _, rt := range r.routes { + // match HTTP method + if rt.method != method { + continue + } + + // match path part number + if len(rt.parts) != len(parts) { + continue + } + + // compare each segment + params := make(map[string]string) + matched := true + for i, seg := range rt.parts { + // parse dynamic parameter + if strings.HasPrefix(seg, ":") { + params[seg[1:]] = parts[i] + } + + // static mismatch + if seg != parts[i] { + matched = false + break + } + } + if matched { + return rt.handler, params + } + } + return nil, nil +} |
