作为一名Python和Django开发人员,我可以独立使用脚本运行项目中的任何代码。
我不太确定如何在Go中实现同样的事情,因为看起来每个Go项目应该只有一个主要的可执行文件。
我想在我的项目中从cronjob调用一个函数,但我不太确定如何添加。在我的main函数中使用标志是我能想到的唯一方法。但是,如果我的脚本本身接受如下所示的额外标志,那么它看起来会非常混乱:
go run server.go --debug --another-flag --script-name <MY-SCRIPT> --my-script-flag-one <FLAG-ONE> --my-script-flag-two <FLAG-TWO>有什么优雅的方法可以做到这一点吗?
发布于 2014-11-26 14:22:07
我在"What is a sensible way to layout a Go project“中引用了文章"Structuring Applications in Go",该文章以项目为例。
该项目包括 cmd packages,每个项目都有自己的选项集。
另一种选择是使用像spf13/cobra这样的CLI接口库,它允许您定义几个命令(相同的exe,不同的选项集)。
Command是应用程序的中心点。
应用程序支持的每个交互都将包含在一个Command中。
命令可以具有子命令,也可以选择运行操作。在示例"hugo server --port=1313“中,'server‘是命令A Command具有以下结构:
type Command struct {
Use string // The one-line usage message.
Short string // The short description shown in the 'help' output.
Long string // The long message shown in the 'help <this-command>' output.
Run func(cmd *Command, args []string) // Run runs the command.
}https://stackoverflow.com/questions/27140130
复制相似问题