【问题标题】:Having multiple main functions on Go在 Go 上有多个主要功能
【发布时间】:2015-01-24 05:57:51
【问题描述】:

作为一名 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>

有什么优雅的方法吗?

【问题讨论】:

标签: go task


【解决方案1】:

我在“What is a sensible way to layout a Go project”中引用了文章“Structuring Applications in Go”,它以项目perkeep为例。
该项目包括several cmd packages,每个都有自己的一组选项。

另一种选择是使用像spf13/cobra 这样的CLI 接口库,它允许您定义多个命令(相同的exe,不同的选项集)。

Command 是应用程序的中心点。
应用程序支持的每个交互都将包含在 Command 中。
命令可以有子命令,并且可以选择运行操作。

在示例“hugo server --port=1313”中,“server”是命令

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.
}

【讨论】:

    猜你喜欢
    • 2012-07-18
    • 1970-01-01
    • 2019-07-04
    • 2011-02-07
    • 1970-01-01
    • 2020-08-12
    • 2011-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多