github.com/15mga/kiwi@v0.0.2-0.20240324021231-b95d5c3ac751/util/cmd.go (about)

     1  package util
     2  
     3  var (
     4  	_Command *Command[M]
     5  )
     6  
     7  func DefaultCmd(m M) {
     8  	_Command = NewCommand[M](m)
     9  }
    10  
    11  func Cmd() *Command[M] {
    12  	return _Command
    13  }
    14  
    15  func NewCommand[T any](data T) *Command[T] {
    16  	return &Command[T]{
    17  		data:          data,
    18  		nameToHandler: make(map[string]CmdHandler[T]),
    19  	}
    20  }
    21  
    22  type CmdHandler[T any] func(T, any) *Err
    23  
    24  type Command[T any] struct {
    25  	data          T
    26  	nameToHandler map[string]CmdHandler[T]
    27  }
    28  
    29  func (c *Command[T]) Data() T {
    30  	return c.data
    31  }
    32  
    33  func (c *Command[T]) Bind(name string, handler CmdHandler[T]) {
    34  	c.nameToHandler[name] = handler
    35  }
    36  
    37  func (c *Command[T]) Unbind(name string) bool {
    38  	if _, ok := c.nameToHandler[name]; !ok {
    39  		return false
    40  	}
    41  	delete(c.nameToHandler, name)
    42  	return true
    43  }
    44  
    45  func (c *Command[T]) Process(name string, data any) *Err {
    46  	handler, ok := c.nameToHandler[name]
    47  	if !ok {
    48  		return NewErr(EcNotExist, M{
    49  			"name": name,
    50  		})
    51  	}
    52  	return handler(c.data, data)
    53  }