新聞中心
這里有您想知道的互聯(lián)網營銷解決方案
創(chuàng)新互聯(lián)GoFrame教程:GoFrame命令管理-基礎方法
?gcmd?組件提供了常用的基礎包方法,可以按照默認的解析規(guī)則,直接獲取命令行參數及選項。

創(chuàng)新互聯(lián)建站專注于中大型企業(yè)的網站制作、成都網站建設和網站改版、網站營銷服務,追求商業(yè)策劃與數據分析、創(chuàng)意藝術與技術開發(fā)的融合,累計客戶1000+,服務滿意度達97%。幫助廣大客戶順利對接上互聯(lián)網浪潮,準確優(yōu)選出符合自己需要的互聯(lián)網運用,我們將一直專注品牌網站設計和互聯(lián)網程序開發(fā),在前進的路上,與客戶一起成長!
常用方法
更多組件方法請參考接口文檔:https://pkg.GO.dev/github.com/gogf/gf/v2/os/gcmd
func Init(args ...string)
func GetArg(index int, def ...string) *gvar.Var
func GetArgAll() []string
func GetOpt(name string, def ...string) *gvar.Var
func GetOptAll() map[string]stringInit自定義命令行
默認情況下,?gcmd?組件會自動從?os.Args?解析獲取參數及數據。我們可以通過?Init?方法自定義命令行數據。使用示例:
func ExampleInit() {
gcmd.Init("gf", "build", "main.go", "-o=gf.exe", "-y")
fmt.Printf(`%#v`, gcmd.GetArgAll())
// Output:
// []string{"gf", "build", "main.go"}
}GetArg*參數獲取
參數獲取可以通過以下兩個方法:
- ?
GetArg?方法用以獲取默認解析的命令行參數,參數通過輸入索引位置獲取,索引位置從?0?開始,但往往我們需要獲取的參數是從?1?開始,因為索引?0?的參數是程序名稱。 - ?
GetArgAll?方法用于獲取所有的命令行參數。
使用示例:
func ExampleGetArg() {
gcmd.Init("gf", "build", "main.go", "-o=gf.exe", "-y")
fmt.Printf(
`Arg[0]: "%v", Arg[1]: "%v", Arg[2]: "%v", Arg[3]: "%v"`,
gcmd.GetArg(0), gcmd.GetArg(1), gcmd.GetArg(2), gcmd.GetArg(3),
)
// Output:
// Arg[0]: "gf", Arg[1]: "build", Arg[2]: "main.go", Arg[3]: ""
}
func ExampleGetArgAll() {
gcmd.Init("gf", "build", "main.go", "-o=gf.exe", "-y")
fmt.Printf(`%#v`, gcmd.GetArgAll())
// Output:
// []string{"gf", "build", "main.go"}
}GetOpt*選項獲取
選項獲取可以通過以下兩個方法:
- ?
GetOpt?方法用以獲取默認解析的命令行選項,選項通過名稱獲取,并且選項的輸入沒有順序性,可以輸入到任意的命令行位置。當給定名稱的選項數據不存在時,返回?nil?。注意判斷不帶數據的選項是否存在時,可以通過?GetOpt(name) != nil?方式。 - ?
GetOptAll?方法用于獲取所有的選項。
使用示例:
func ExampleGetOpt() {
gcmd.Init("gf", "build", "main.go", "-o=gf.exe", "-y")
fmt.Printf(
`Opt["o"]: "%v", Opt["y"]: "%v", Opt["d"]: "%v"`,
gcmd.GetOpt("o"), gcmd.GetOpt("y"), gcmd.GetOpt("d", "default value"),
)
// Output:
// Opt["o"]: "gf.exe", Opt["y"]: "", Opt["d"]: "default value"
}
func ExampleGetOptAll() {
gcmd.Init("gf", "build", "main.go", "-o=gf.exe", "-y")
fmt.Printf(`%#v`, gcmd.GetOptAll())
// May Output:
// map[string]string{"o":"gf.exe", "y":""}
}GetOptWithEnv特性
func GetOptWithEnv(key string, def ...interface{}) *gvar.Var該方法用于獲取命令行中指定的選項數值,如果該選項不存在時,則從環(huán)境變量中讀取。但是兩者的名稱規(guī)則會不一樣。例如:?gcmd.GetOptWithEnv("gf.debug")?將會優(yōu)先去讀取命令行中的?gf.debug?選項,當不存在時,則會去讀取?GF_DEBUG?環(huán)境變量。
需要注意的是參數命名轉換規(guī)則:
- 環(huán)境變量會將名稱轉換為大寫,名稱中的?
.?字符轉換為?_?字符。 - 命令行中會將名稱轉換為小寫,名稱中的?
_?字符轉換為?.?字符。
使用示例:
func ExampleGetOptWithEnv() {
fmt.Printf("Opt[gf.test]:%s\n", gcmd.GetOptWithEnv("gf.test"))
_ = genv.Set("GF_TEST", "YES")
fmt.Printf("Opt[gf.test]:%s\n", gcmd.GetOptWithEnv("gf.test"))
// Output:
// Opt[gf.test]:
// Opt[gf.test]:YES
} 分享名稱:創(chuàng)新互聯(lián)GoFrame教程:GoFrame命令管理-基礎方法
文章位置:http://m.5511xx.com/article/copschh.html


咨詢
建站咨詢
