github.com/gnolang/gno@v0.0.0-20240520182011-228e9d0192ce/tm2/pkg/sdk/router.go (about)

     1  package sdk
     2  
     3  import (
     4  	"fmt"
     5  )
     6  
     7  type router struct {
     8  	routes map[string]Handler
     9  }
    10  
    11  var _ Router = NewRouter()
    12  
    13  // NewRouter returns a reference to a new router.
    14  func NewRouter() *router { //nolint: golint
    15  	return &router{
    16  		routes: make(map[string]Handler),
    17  	}
    18  }
    19  
    20  // AddRoute adds a route path to the router with a given handler. The route must
    21  // be alphanumeric.
    22  func (rtr *router) AddRoute(path string, h Handler) Router {
    23  	if !isAlphaNumeric(path) {
    24  		panic("route expressions can only contain alphanumeric characters")
    25  	}
    26  	if rtr.routes[path] != nil {
    27  		panic(fmt.Sprintf("route %s has already been initialized", path))
    28  	}
    29  
    30  	rtr.routes[path] = h
    31  	return rtr
    32  }
    33  
    34  // Route returns a handler for a given route path.
    35  func (rtr *router) Route(path string) Handler {
    36  	return rtr.routes[path]
    37  }