summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorEltrac <hi@guhub.cn>2025-11-27 11:27:49 +0800
committerEltrac <hi@guhub.cn>2025-11-27 11:27:49 +0800
commita13c9a7abe43e9e3f21799e8be161422c7fad5a4 (patch)
tree374bf08085a8713ed926a5f1983286fdf38beea6
parent21660af7bef5e7a0e679fcbd8bee7352642b24f8 (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.go25
-rw-r--r--router.go14
2 files changed, 22 insertions, 17 deletions
diff --git a/api.go b/api.go
index 5682b99..cc35c57 100644
--- a/api.go
+++ b/api.go
@@ -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)
+}
diff --git a/router.go b/router.go
index 86d706a..d608784 100644
--- a/router.go
+++ b/router.go
@@ -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,
- })
-}