github.com/kaiya/goutils@v1.0.1-0.20230226104005-4ae4a4dc3688/http/router/router.go (about) 1 package router 2 3 import ( 4 "net/http" 5 6 "gitlab.momoso.com/cm/kit/third_party/lg" 7 ) 8 9 type middleware func(http.Handler) http.Handler 10 11 type Router struct { 12 middlewareChain []middleware 13 mux map[string]http.Handler 14 } 15 16 func NewRouter() *Router { 17 return &Router{} 18 } 19 20 func (r *Router) Use(m middleware) { 21 r.middlewareChain = append(r.middlewareChain, m) 22 } 23 24 func (r *Router) Add(route string, h http.Handler) { 25 var mergedHandler = h 26 for i := len(r.middlewareChain) - 1; i >= 0; i-- { 27 mergedHandler = r.middlewareChain[i](mergedHandler) 28 } 29 if r.mux == nil { 30 r.mux = make(map[string]http.Handler) 31 } 32 r.mux[route] = mergedHandler 33 } 34 35 func (r *Router) ServeHTTP(rw http.ResponseWriter, req *http.Request) { 36 path := req.URL.Path 37 lg.Infof("req path:%s", path) 38 if handler, ok := r.mux[path]; ok { 39 lg.Infof("path matched") 40 handler.ServeHTTP(rw, req) 41 lg.Infof("router serve done") 42 } 43 }