作为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>
Run Code Online (Sandbox Code Playgroud)
这样做有什么优雅的方式吗?
Von*_*onC 11
我参考了" 在Go项目中布局应用程序的什么是一种明智的方法 "文章" 在Go中构建应用程序 ",该项目以项目camlistore为例.
该项目包括几个 cmd包,每个包都有自己的选项集.
另一种选择是使用CLI接口库spf13/cobra,它允许您定义几个命令(相同的exe,单独的选项集).
Command是应用程序的中心点.
应用程序支持的每个交互都将包含在a中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.
}
Run Code Online (Sandbox Code Playgroud)