github.com/seeker-insurance/kit@v0.0.13/web/routing.go (about)

     1  package web
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/labstack/echo"
     7  )
     8  
     9  type MethodHandler struct {
    10  	Method     string
    11  	Handler    echo.HandlerFunc
    12  	MiddleWare []echo.MiddlewareFunc
    13  }
    14  
    15  type Route struct {
    16  	Path     string
    17  	Handlers []*MethodHandler
    18  	Name     string
    19  	ERoute   *echo.Route
    20  }
    21  
    22  type RouteConfig struct {
    23  	Routes     []*Route
    24  	MiddleWare []echo.MiddlewareFunc
    25  }
    26  
    27  func (route *Route) Handle(m string, hf HandlerFunc, mw ...echo.MiddlewareFunc) *Route {
    28  	handler := &MethodHandler{m, wrapApiRoute(hf), mw}
    29  	route.Handlers = append(route.Handlers, handler)
    30  	return route
    31  }
    32  
    33  func (route *Route) SetName(n string) *Route {
    34  	route.Name = n
    35  	return route
    36  }
    37  
    38  func (config *RouteConfig) AddRoute(path string) *Route {
    39  	route := &Route{
    40  		Path:     path,
    41  		Handlers: []*MethodHandler{},
    42  	}
    43  	config.Routes = append(config.Routes, route)
    44  	return route
    45  }
    46  
    47  func newRouteConfig() *RouteConfig {
    48  	return &RouteConfig{[]*Route{}, []echo.MiddlewareFunc{}}
    49  }
    50  
    51  var Routing *RouteConfig
    52  
    53  func init() {
    54  	Routing = &RouteConfig{[]*Route{}, []echo.MiddlewareFunc{}}
    55  }
    56  
    57  func AddRoute(path string) *Route {
    58  	return Routing.AddRoute(path)
    59  }
    60  func routeByName(cfg *RouteConfig, name string) (*Route, error) {
    61  	for _, r := range cfg.Routes {
    62  		if r.Name == name {
    63  			return r, nil
    64  		}
    65  	}
    66  	return nil, fmt.Errorf("Could not find route with name %v", name)
    67  }
    68  
    69  func RouteByName(name string) (*Route, error) {
    70  	return routeByName(Routing, name)
    71  }
    72  
    73  type HandlerFunc func(ApiContext) error
    74  
    75  func wrapApiRoute(f HandlerFunc) echo.HandlerFunc {
    76  	return func(c echo.Context) error {
    77  		return f(c.(ApiContext))
    78  	}
    79  }
    80  
    81  func InitRoutes(e *echo.Echo) {
    82  	initRoutes(e, Routing)
    83  }
    84  
    85  func initRoutes(e *echo.Echo, cfg *RouteConfig) {
    86  	for _, route := range cfg.Routes {
    87  		initRoute(e, route)
    88  	}
    89  }
    90  func initRoute(e *echo.Echo, route *Route) {
    91  	for _, handler := range route.Handlers {
    92  		er := e.Add(handler.Method, route.Path, handler.Handler, handler.MiddleWare...)
    93  		er.Name = route.Name
    94  		route.ERoute = er
    95  	}
    96  }