如何使用属于 Web 应用程序的 CLI Go 文件?

huangapple go评论87阅读模式
英文:

How can I use cli Go files that belong to a web app?

问题

我的问题与Go应用程序的结构或方法有关。我有以下应用程序。

root
  |- app
  | |- services
  | |- repositories
  | |- handlers
  | |- commands
  |- go.mod
  |- main.go

commands包中的Go文件是独立工作的。其余的包是为Web应用程序工作的。我在main.go中启动了一个HTTP Web服务器。

因此,我想在crontab中运行commands包中的Go文件。但是据我所知,我将把这些整个包构建成一个单独的二进制文件。我的问题是如何在crontab中独立运行commands包中的Go文件?我认为我应该将它们分成两个应用程序,例如"web app"和"command app",但实际上它们彼此相关,我不想以不同的方式管理两个应用程序。我可以在crontab中使用commands包中的Go文件,另一方面在main.go中启动一个HTTP Web服务器吗?

英文:

My question is related to the structure or approach of Go applications. I have got the following application.

root
  |- app
  | |- services
  | |- repositories
  | |- handlers
  | |- commands
  |- go.mod
  |- main.go

The Go files in the commands package are working independently. The rest of the packages are working for a web application. I start an HTTP web server in the main.go

So, I'd like to run the Go files in the commands packages in the crontab. But as I know, I'll build these whole packages into a single binary file. My question is how can I run the Go files in the commands packages independently in the crontab? I think I should separate them into 2 applications such as "web app" and "command app" but actually they are related to each other and I don't want to manage 2 apps differently. May I use commands Go files in the crontab and on the other hand start an HTTP web server in the main.go?

答案1

得分: 1

你可以将一个Web应用程序模块中的包导入到另一个模块中,没有任何理由不这样做。但是,如果你想将它们放在一起,你可以按照常见的做法,在特定的目录中添加额外的main包,创建如下的目录结构:

root
  |- app
  |  |-services
  |  |-...
  |- cmd
  |   |- tools
  |   |   |- main.go
  |- main.go

你可以通过运行go build ./cmd/toolsgo install ./cmd/tools来构建/安装你的CLI二进制文件。

英文:

There's no reason why you can't import packages from your web application module into another one, but if you want to keep them together, you can just do what is quite common, and add additional main packages in specific directories, giving a directory structure like this:

root
  |- app
  |  |-services
  |  |-...
  |- cmd
  |   |- tools
  |   |   |- main.go
  |- main.go

You can build/install your CLI binary simply by running go build ./cmd/tools or go install ./cmd/tools

huangapple
  • 本文由 发表于 2021年10月27日 19:12:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/69737604.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定