gcmd_parser_handler.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // Copyright 2019 gf Author(https://github.com/gogf/gf). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. //
  7. package gcmd
  8. import (
  9. "errors"
  10. )
  11. // BindHandle registers callback function <f> with <cmd>.
  12. func (p *Parser) BindHandle(cmd string, f func()) error {
  13. if _, ok := p.commandFuncMap[cmd]; ok {
  14. return errors.New("duplicated handle for command:" + cmd)
  15. } else {
  16. p.commandFuncMap[cmd] = f
  17. }
  18. return nil
  19. }
  20. // BindHandle registers callback function with map <m>.
  21. func (p *Parser) BindHandleMap(m map[string]func()) error {
  22. var err error
  23. for k, v := range m {
  24. if err = p.BindHandle(k, v); err != nil {
  25. return err
  26. }
  27. }
  28. return err
  29. }
  30. // RunHandle executes the callback function registered by <cmd>.
  31. func (p *Parser) RunHandle(cmd string) error {
  32. if handle, ok := p.commandFuncMap[cmd]; ok {
  33. handle()
  34. } else {
  35. return errors.New("no handle found for command:" + cmd)
  36. }
  37. return nil
  38. }
  39. // AutoRun automatically recognizes and executes the callback function
  40. // by value of index 0 (the first console parameter).
  41. func (p *Parser) AutoRun() error {
  42. if cmd := p.GetArg(1); cmd != "" {
  43. if handle, ok := p.commandFuncMap[cmd]; ok {
  44. handle()
  45. } else {
  46. return errors.New("no handle found for command:" + cmd)
  47. }
  48. } else {
  49. return errors.New("no command found")
  50. }
  51. return nil
  52. }