2018-01-20 20:08:00 -08:00
|
|
|
package baseapp
|
2018-01-12 11:49:53 -08:00
|
|
|
|
2018-01-12 13:59:19 -08:00
|
|
|
import (
|
|
|
|
"regexp"
|
|
|
|
|
|
|
|
sdk "github.com/cosmos/cosmos-sdk/types"
|
|
|
|
)
|
|
|
|
|
2018-02-16 16:52:07 -08:00
|
|
|
// Router provides handlers for each transaction type.
|
2018-01-12 11:49:53 -08:00
|
|
|
type Router interface {
|
2018-04-02 08:13:37 -07:00
|
|
|
AddRoute(r string, h sdk.Handler) (rtr Router)
|
2018-01-12 13:59:19 -08:00
|
|
|
Route(path string) (h sdk.Handler)
|
2018-01-12 11:49:53 -08:00
|
|
|
}
|
|
|
|
|
2018-03-27 11:00:27 -07:00
|
|
|
// map a transaction type to a handler and an initgenesis function
|
2018-01-12 11:49:53 -08:00
|
|
|
type route struct {
|
|
|
|
r string
|
2018-01-12 13:59:19 -08:00
|
|
|
h sdk.Handler
|
2018-01-12 11:49:53 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
type router struct {
|
|
|
|
routes []route
|
|
|
|
}
|
|
|
|
|
2018-02-02 17:09:20 -08:00
|
|
|
// nolint
|
|
|
|
// NewRouter - create new router
|
|
|
|
// TODO either make Function unexported or make return type (router) Exported
|
2018-01-15 17:38:56 -08:00
|
|
|
func NewRouter() *router {
|
|
|
|
return &router{
|
2018-01-12 13:59:19 -08:00
|
|
|
routes: make([]route, 0),
|
2018-01-12 11:49:53 -08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
var isAlpha = regexp.MustCompile(`^[a-zA-Z]+$`).MatchString
|
|
|
|
|
2018-02-02 17:09:20 -08:00
|
|
|
// AddRoute - TODO add description
|
2018-04-02 08:13:37 -07:00
|
|
|
func (rtr *router) AddRoute(r string, h sdk.Handler) Router {
|
2018-01-12 11:49:53 -08:00
|
|
|
if !isAlpha(r) {
|
|
|
|
panic("route expressions can only contain alphanumeric characters")
|
|
|
|
}
|
2018-04-02 08:13:37 -07:00
|
|
|
rtr.routes = append(rtr.routes, route{r, h})
|
2018-02-26 05:02:03 -08:00
|
|
|
|
|
|
|
return rtr
|
2018-01-12 11:49:53 -08:00
|
|
|
}
|
|
|
|
|
2018-03-27 11:00:27 -07:00
|
|
|
// Route - TODO add description
|
2018-03-27 12:46:06 -07:00
|
|
|
// TODO handle expressive matches.
|
2018-01-15 17:38:56 -08:00
|
|
|
func (rtr *router) Route(path string) (h sdk.Handler) {
|
2018-01-12 11:49:53 -08:00
|
|
|
for _, route := range rtr.routes {
|
2018-03-27 12:46:06 -07:00
|
|
|
if route.r == path {
|
2018-01-12 11:49:53 -08:00
|
|
|
return route.h
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|