gcmd_handler.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // Copyright GoFrame Author(https://goframe.org). 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. "github.com/gogf/gf/errors/gcode"
  10. "github.com/gogf/gf/errors/gerror"
  11. )
  12. // BindHandle registers callback function <f> with <cmd>.
  13. func BindHandle(cmd string, f func()) error {
  14. if _, ok := defaultCommandFuncMap[cmd]; ok {
  15. return gerror.NewCode(gcode.CodeInvalidOperation, "duplicated handle for command:"+cmd)
  16. } else {
  17. defaultCommandFuncMap[cmd] = f
  18. }
  19. return nil
  20. }
  21. // BindHandleMap registers callback function with map <m>.
  22. func BindHandleMap(m map[string]func()) error {
  23. var err error
  24. for k, v := range m {
  25. if err = BindHandle(k, v); err != nil {
  26. return err
  27. }
  28. }
  29. return err
  30. }
  31. // RunHandle executes the callback function registered by <cmd>.
  32. func RunHandle(cmd string) error {
  33. if handle, ok := defaultCommandFuncMap[cmd]; ok {
  34. handle()
  35. } else {
  36. return gerror.NewCode(gcode.CodeMissingConfiguration, "no handle found for command:"+cmd)
  37. }
  38. return nil
  39. }
  40. // AutoRun automatically recognizes and executes the callback function
  41. // by value of index 0 (the first console parameter).
  42. func AutoRun() error {
  43. if cmd := GetArg(1); cmd != "" {
  44. if handle, ok := defaultCommandFuncMap[cmd]; ok {
  45. handle()
  46. } else {
  47. return gerror.NewCode(gcode.CodeMissingConfiguration, "no handle found for command:"+cmd)
  48. }
  49. } else {
  50. return gerror.NewCode(gcode.CodeMissingParameter, "no command found")
  51. }
  52. return nil
  53. }