summaryrefslogtreecommitdiff
path: root/router.go
diff options
context:
space:
mode:
authorEltrac <hi@guhub.cn>2025-11-27 10:36:15 +0800
committerEltrac <hi@guhub.cn>2025-11-27 10:36:15 +0800
commita52afde13b4e483e5dd96c7d1a3ace81ce400103 (patch)
treef4914a5e788417cddf9ee039ce1a205141c1f7f8 /router.go
parenta555355d69a4fe9cd01d8bea86ce5b057cd1cd66 (diff)
feat: get router working properly and implement basic methods
Diffstat (limited to 'router.go')
-rw-r--r--router.go21
1 files changed, 19 insertions, 2 deletions
diff --git a/router.go b/router.go
index 5428701..a9137be 100644
--- a/router.go
+++ b/router.go
@@ -1,6 +1,7 @@
package growel
import (
+ "net/http"
"strings"
)
@@ -18,12 +19,12 @@ func NewRouter() *Router {
return &Router{}
}
-func (r *Router) Add(method, path string, h Handler) {
+func (r *Router) Add(method string, 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) {
+func (r *Router) Find(method string, path string) (Handler, map[string]string) {
parts := strings.Split(path, "/")
for _, rt := range r.routes {
@@ -37,13 +38,16 @@ func (r *Router) Find(method, path string) (Handler, map[string]string) {
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]
+ continue
}
// static mismatch
@@ -58,3 +62,16 @@ func (r *Router) Find(method, path string) (Handler, map[string]string) {
}
return nil, nil
}
+
+func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
+ handler, params := r.Find(req.Method, req.URL.Path)
+ if handler == nil {
+ http.NotFound(w, req)
+ return
+ }
+ handler(&Context{
+ W: w,
+ R: req,
+ Params: params,
+ })
+}