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