go - 在 Go 上有多个主要功能

标签 go task

作为一名 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 a Command.
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/

相关文章:

regex - Go 中的 "Unknown escape sequence"错误

mysql - 使用 SET 变量进行 MySQL 查询

go - 如何在拦截器中安全地将值添加到grpc ServerStream

c# - 此代码应返回 Task 还是 Task<object>?

c++ - 我是否需要在单语言 UWP 应用程序中使用 create_async?

ruby-on-rails - 如何编写使用 args 运行多个任务的任务?

go - 如何将 HTTP 响应写入标准输出?

google-app-engine - 使用 Go 完成常见的 App Engine 处理程序任务

c# - 创建同步请求的 .net 异步包装器

android - 如何知道 Android 任务的可见性变化?