diff options
| author | Eltrac <hi@guhub.cn> | 2025-11-27 11:27:49 +0800 |
|---|---|---|
| committer | Eltrac <hi@guhub.cn> | 2025-11-27 11:27:49 +0800 |
| commit | a13c9a7abe43e9e3f21799e8be161422c7fad5a4 (patch) | |
| tree | 374bf08085a8713ed926a5f1983286fdf38beea6 | |
| parent | 21660af7bef5e7a0e679fcbd8bee7352642b24f8 (diff) | |
refactor: move ServeHTTP impl to api.go router.go should just handle routes and
find the right handler, while api.go (the engine) is the one who should serve.
| -rw-r--r-- | api.go | 25 | ||||
| -rw-r--r-- | router.go | 14 |
2 files changed, 22 insertions, 17 deletions
@@ -8,15 +8,15 @@ type Api struct { router *Router } +// create API engine + func New() *Api { var a Api a.router = NewRouter() return &a } -func (api *Api) Start(port string) { - http.ListenAndServe(port, api.router) -} +// add routes func (api *Api) GET(path string, h Handler) { api.router.Add("GET", path, h) @@ -33,3 +33,22 @@ func (api *Api) PUT(path string, h Handler) { func (api *Api) DELETE(path string, h Handler) { api.router.Add("DELETE", path, h) } + +// serve and start + +func (a *Api) ServeHTTP(w http.ResponseWriter, req *http.Request) { + handler, params := a.router.Find(req.Method, req.URL.Path) + if handler == nil { + http.NotFound(w, req) + return + } + handler(&Context{ + W: w, + R: req, + Params: params, + }) +} + +func (api *Api) Start(port string) { + http.ListenAndServe(port, api) +} @@ -1,7 +1,6 @@ package growel import ( - "net/http" "strings" ) @@ -65,16 +64,3 @@ func (r *Router) Find(method string, 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, - }) -} |
