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

     1  package types
     2  
     3  import (
     4  	"fmt"
     5  
     6  	sdk "github.com/Finschia/finschia-sdk/types"
     7  	"github.com/Finschia/finschia-sdk/x/evidence/exported"
     8  )
     9  
    10  type (
    11  	// Handler defines an agnostic Evidence handler. The handler is responsible
    12  	// for executing all corresponding business logic necessary for verifying the
    13  	// evidence as valid. In addition, the Handler may execute any necessary
    14  	// slashing and potential jailing.
    15  	Handler func(sdk.Context, exported.Evidence) error
    16  
    17  	// Router defines a contract for which any Evidence handling module must
    18  	// implement in order to route Evidence to registered Handlers.
    19  	Router interface {
    20  		AddRoute(r string, h Handler) Router
    21  		HasRoute(r string) bool
    22  		GetRoute(path string) Handler
    23  		Seal()
    24  		Sealed() bool
    25  	}
    26  
    27  	router struct {
    28  		routes map[string]Handler
    29  		sealed bool
    30  	}
    31  )
    32  
    33  func NewRouter() Router {
    34  	return &router{
    35  		routes: make(map[string]Handler),
    36  	}
    37  }
    38  
    39  // Seal prevents the router from any subsequent route handlers to be registered.
    40  // Seal will panic if called more than once.
    41  func (rtr *router) Seal() {
    42  	if rtr.sealed {
    43  		panic("router already sealed")
    44  	}
    45  	rtr.sealed = true
    46  }
    47  
    48  // Sealed returns a boolean signifying if the Router is sealed or not.
    49  func (rtr router) Sealed() bool {
    50  	return rtr.sealed
    51  }
    52  
    53  // AddRoute adds a governance handler for a given path. It returns the Router
    54  // so AddRoute calls can be linked. It will panic if the router is sealed.
    55  func (rtr *router) AddRoute(path string, h Handler) Router {
    56  	if rtr.sealed {
    57  		panic(fmt.Sprintf("router sealed; cannot register %s route handler", path))
    58  	}
    59  	if !sdk.IsAlphaNumeric(path) {
    60  		panic("route expressions can only contain alphanumeric characters")
    61  	}
    62  	if rtr.HasRoute(path) {
    63  		panic(fmt.Sprintf("route %s has already been registered", path))
    64  	}
    65  
    66  	rtr.routes[path] = h
    67  	return rtr
    68  }
    69  
    70  // HasRoute returns true if the router has a path registered or false otherwise.
    71  func (rtr *router) HasRoute(path string) bool {
    72  	return rtr.routes[path] != nil
    73  }
    74  
    75  // GetRoute returns a Handler for a given path.
    76  func (rtr *router) GetRoute(path string) Handler {
    77  	if !rtr.HasRoute(path) {
    78  		panic(fmt.Sprintf("route does not exist for path %s", path))
    79  	}
    80  	return rtr.routes[path]
    81  }