diff options
| author | Eltrac <hi@guhub.cn> | 2025-11-27 10:36:15 +0800 |
|---|---|---|
| committer | Eltrac <hi@guhub.cn> | 2025-11-27 10:36:15 +0800 |
| commit | a52afde13b4e483e5dd96c7d1a3ace81ce400103 (patch) | |
| tree | f4914a5e788417cddf9ee039ce1a205141c1f7f8 | |
| parent | a555355d69a4fe9cd01d8bea86ce5b057cd1cd66 (diff) | |
feat: get router working properly and implement basic methods
| -rw-r--r-- | api.go | 35 | ||||
| -rw-r--r-- | context.go | 10 | ||||
| -rw-r--r-- | router.go | 21 |
3 files changed, 46 insertions, 20 deletions
@@ -1,18 +1,35 @@ package growel import ( - + "net/http" ) -type growel struct { } +type Api struct { + router *Router +} + +func New() *Api { + var a Api + a.router = NewRouter() + return &a +} + +func (api *Api) Start(port string) { + http.ListenAndServe(port, api.router) +} -func (growel) New() (*growel) { - return &growel{} +func (api *Api) GET(path string, h Handler) { + api.router.Add("GET", path, h) } -func (*growel) GET() {} -func (*growel) POST() {} -func (*growel) PUT() {} -func (*growel) DELETE() {} +func (api *Api) POST(path string, h Handler) { + api.router.Add("POST", path, h) +} -func (*growel) Start() {} +func (api *Api) PUT(path string, h Handler) { + api.router.Add("PUT", path, h) +} + +func (api *Api) DELETE(path string, h Handler) { + api.router.Add("DELETE", path, h) +} @@ -6,16 +6,8 @@ import ( type Context struct { W http.ResponseWriter - R http.Request + R *http.Request Params map[string]string } type Handler func(c *Context) - -func (h Handler) ServeHTTP(w http.ResponseWriter, r http.Request) { - h(&Context{ - W: w, - R: r, - Params: make(map[string]string), - }) -} @@ -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, + }) +} |
