我试着用golang弄脏手。所以我发明了一个小项目,并希望用不同的命令构建一个小型控制台应用程序。
我找到codegangsta/cli并尝试了这个例子。
package main
import (
"os"
"github.com/codegangsta/cli"
)
func main() {
app := cli.NewApp()
app.Commands = []cli.Command{
{
Name: "add",
Usage: "add a task to the list",
Action: func(c *cli.Context) {
println("added task: ", c.Args().First())
},
},
{
Name: "complete",
Usage: "complete a task on the list",
Action: func(c *cli.Context) {
println("completed task: ", c.Args().First())
},
},
}
app.Run(os.Args)
}
现在我想把Commands-array中的命令放在单独的文件中,只引用它们。
我怎样才能做到这一点?
感谢您的一些建议。
答案 0 :(得分:3)
以下是分割文件的几种方法之一:
在文件main.go中:
package main
import (
"os"
"github.com/codegangsta/cli"
)
func main() {
app := cli.NewApp()
app.Commands = []cli.Command{
addCommand,
completeCommand,
}
app.Run(os.Args)
}
在文件comamnds.go中写道:
package main
import (
"github.com/codegangsta/cli"
)
var addCommand = cli.Command{
Name: "add",
Usage: "add a task to the list",
Action: func(c *cli.Context) {
println("added task: ", c.Args().First())
},
}
var completeCommand cli.Command{
Name: "complete",
Usage: "complete a task on the list",
Action: func(c *cli.Context) {
println("completed task: ", c.Args().First())
},
}