github.com/Finschia/finschia-sdk@v0.48.1/x/gov/types/router.go (about)

     1  package types
     2  
     3  import (
     4  	"fmt"
     5  
     6  	sdk "github.com/Finschia/finschia-sdk/types"
     7  )
     8  
     9  var _ Router = (*router)(nil)
    10  
    11  // Router implements a governance Handler router.
    12  //
    13  // TODO: Use generic router (ref #3976).
    14  type Router interface {
    15  	AddRoute(r string, h Handler) (rtr Router)
    16  	HasRoute(r string) bool
    17  	GetRoute(path string) (h Handler)
    18  	Seal()
    19  }
    20  
    21  type router struct {
    22  	routes map[string]Handler
    23  	sealed bool
    24  }
    25  
    26  // NewRouter creates a new Router interface instance
    27  func NewRouter() Router {
    28  	return &router{
    29  		routes: make(map[string]Handler),
    30  	}
    31  }
    32  
    33  // Seal seals the router which prohibits any subsequent route handlers to be
    34  // added. Seal will panic if called more than once.
    35  func (rtr *router) Seal() {
    36  	if rtr.sealed {
    37  		panic("router already sealed")
    38  	}
    39  	rtr.sealed = true
    40  }
    41  
    42  // AddRoute adds a governance handler for a given path. It returns the Router
    43  // so AddRoute calls can be linked. It will panic if the router is sealed.
    44  func (rtr *router) AddRoute(path string, h Handler) Router {
    45  	if rtr.sealed {
    46  		panic("router sealed; cannot add route handler")
    47  	}
    48  
    49  	if !sdk.IsAlphaNumeric(path) {
    50  		panic("route expressions can only contain alphanumeric characters")
    51  	}
    52  	if rtr.HasRoute(path) {
    53  		panic(fmt.Sprintf("route %s has already been initialized", path))
    54  	}
    55  
    56  	rtr.routes[path] = h
    57  	return rtr
    58  }
    59  
    60  // HasRoute returns true if the router has a path registered or false otherwise.
    61  func (rtr *router) HasRoute(path string) bool {
    62  	return rtr.routes[path] != nil
    63  }
    64  
    65  // GetRoute returns a Handler for a given path.
    66  func (rtr *router) GetRoute(path string) Handler {
    67  	if !rtr.HasRoute(path) {
    68  		panic(fmt.Sprintf("route \"%s\" does not exist", path))
    69  	}
    70  
    71  	return rtr.routes[path]
    72  }