作为一名 Python 和 Django 开发人员,我可以使用脚本独立运行项目中的任何代码。
我不太清楚如何在 Go 中实现相同的目标,因为看起来每个 Go 项目应该只有一个主要的可执行文件。
我想从 cronjob 调用我项目中的一个函数,但我不太确定如何添加它。在我的主要功能中使用标志是我能想到的唯一方法。但是,如果我的脚本本身接受额外的标志,它看起来会很困惑,如下所示:
go run server.go --debug --another-flag --script-name <MY-SCRIPT> --my-script-flag-one <FLAG-ONE> --my-script-flag-two <FLAG-TWO>
有什么优雅的方法吗?
最佳答案
我在“What is a sensible way to layout a Go project ”中引用了文章“Structuring Applications in Go ”,它以项目 perkeep 为例。
该项目包括several cmd packages ,每个都有自己的一组选项。
另一种选择是使用 CLI 接口(interface)库,如 spf13/cobra
,它允许您定义多个命令(相同的 exe,不同的选项集)。
Command
is the central point of the application.
Each interaction that the application supports will be contained in aCommand
.
A command can have children commands and optionally run an action.
In the example "
hugo server --port=1313
", 'server
' is the command
A
Command
has the following structure:
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.
}
关于go - 在 Go 上有多个主要功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27140130/