必须能够从命令行界面独立使用的 Golang 包。

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

Golang package that must also be useable standalone from cli

问题

我想创建一个包含主函数并使用flag包指定参数的包。

此外,我希望能够将此包包含在其他包中,并使用类似于在命令行传递参数的语法来调用其方法。可能是这样的:

err := myPackage.setFlags(args ...string)
out, err := myPackage.exec()

我希望包含的包具有主函数的一些原因是:

  • 它使我能够将包作为独立的可执行文件分发。我的用户可能不需要完整的系统。

  • 这可能会使手动故障排除更容易。

我应该保持一切分开并使用os/exec吗?

我应该为每个包创建独立的包装器(也许可以生成这些包装器?),并直接从完整系统中调用导出的函数,而不进行setFlags操作吗?

有没有好的设计模式可以遵循这样做?

或者我是在构思一个反模式吗?

英文:

I would like to create a package that has a main function and uses the flag package to specify arguments.

Additionally, I want to be able to include this package in other packages, and call it's methods with a similar syntax to passing args on the cli. Possibly something like

err := myPackage.setFlags(args ...string)
out, err := myPackage.exec() 

Some of the reasons I want the included package to have a main function is:

  • It enables me to distribute the package as a standalone executable. My users might not need the complete system

  • It could make manual troubleshooting easier

Should I keep everything separate and use os\exec?

Should I create standalone wrappers (maybe these can be generated?) for each package and call exported functions directly from the complete system without doing the setFlags thing?

Is there a good design pattern I could follow to do this?

Or am I conjuring up an anti-pattern?

答案1

得分: 2

一个常见的模式是在项目中有一个cmd包,其中包含可执行文件。

类似于这样的结构:

cmd/
   foo/main.go
pkg/
   foo/foo.go

cmd/foo导入pkg/foo并处理命令行标志。pkg/foo是包含所有库代码的包。这种模式允许其他人导入pkg/foo,而cmd/foo还提供了一个名为foo的可执行文件。

英文:

A common pattern is to have a cmd pkg in your project that has executables.

Something like this

cmd/
   foo/main.go
pkg/
   foo/foo.go

cmd/foo imports pkg/foo and handles the command line flags. pkg/foo is the package with all of the library code. This pattern lets others import pkg/foo and cmd/foo gives you an executable called foo as well.

huangapple
  • 本文由 发表于 2016年8月21日 04:10:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/39058288.html
匿名

发表评论

匿名网友

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

确定