目前正在使用Codegangsta's Cli Library。我像这样运行一个命令:
myGoProgram arg1 arg2 arg3 --flag1 flag1arg
正在运行
app.Action = func(c *cli.Context) {
fmt.Println("Context: ", c.Args())
}
返回:[arg1 arg2 arg3 --flag1 flag1arg]
(c.Args()'s return type)
如何访问arg1
,arg2
和arg3
,而不是--flag1
或flag1arg
?我是否必须遍历此数组?
答案 0 :(得分:0)
好的,我所做的就是创建两个相同内容的数组,并相应地删除元素,以创建仅包含原始命令的数组。
func noFlagCliArgs(cliArgs []string) []string {
a := cliArgs
for pos, arg := range cliArgs {
if strings.Compare(string(arg[0]), "-") == 0 {
// Cut out two to get rid of flag and its argument
a = append(a[:pos], a[pos+2:]...)
}
}
return a
}
答案 1 :(得分:0)
我认为你可能没有正确定义你的旗帜,看看我做的这个例子:
package main
import (
"fmt"
"os"
"github.com/codegangsta/cli"
)
func main() {
app := cli.NewApp()
app.Name = "so-example"
app.Usage = "Demonstrate CLI usage"
app.Commands = []cli.Command{
{
Name: "one",
Usage: "first thing",
Flags: []cli.Flag{
cli.StringFlag{
Name: "test",
Value: "foobar",
Usage: "something cool",
},
},
Action: func(c *cli.Context) {
fmt.Println("completed task", c.Command.Name, " with args ", c.Args())
if (c.String("test") != "foobar") {
fmt.Println("Where'd foobar go?")
}
},
},
{
Name: "two",
Usage: "second thing",
Flags: []cli.Flag{
cli.StringFlag{
Name: "test",
Value: "foobar",
Usage: "something cool",
},
},
Action: func(c *cli.Context) {
fmt.Println("completed task", c.Command.Name, " with args ", c.Args())
fmt.Println("Testing value:", c.String("test"))
if (c.String("test") != "foobar") {
fmt.Println("Where'd foobar go?")
}
},
},
}
app.Run(os.Args)
}
$ ./sandbox two foo bar hello world
completed task two with args [foo bar hello world]
Testing value: foobar
$ ./sandbox two foo bar hello world --test "see"
completed task two with args [foo bar hello world]
Testing value: see
Where'd foobar go?