英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论