还必须可以独立于cli使用的Golang软件包

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?

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.