@amit this was my best way : NewFlagSet. This is full example including 
testing: https://eli.thegreenplace.net/2020/testing-flag-parsing-in-go-programs/

Best

On Sunday, April 25, 2021 at 5:43:35 AM UTC+3 amits...@gmail.com wrote:

> On Sun, Apr 25, 2021 at 7:10 AM Shivendra Singh
> <shivendra...@gmail.com> wrote:
> >
> > Yes @Jan Mercl absolutely correct!!
> >
> > Able to figure out a solution.
> > Basically the go mod i am using as part of the code is doing something 
> like this :
> > func init() {
> > //reads vars
> > flag.Parse()
> > }
> >
> > The problem arises when doing flag.Parse() as part of the init.
> > https://github.com/golang/go/issues/31859#issuecomment-489889428 gives 
> very valuable insights to the issue.
> >
> > High Level Problems that may occur :
> > 1. if i am reading any command line args anywhere else it will fail, 
> since in this code flag.Parse() is happening during init()
> > 2. The code snippet :
> > var _ = func() bool {
> > testing.Init()
> > return true
> > }()
> > This somewhat of a hack to explicitly invoke init() method and only 
> helps in a very few cases.
> >
> > As a solution, i went ahead to remove the flag.Parse() from init() 
> because it is really wrong and rather call it from my main().
> > Just doing this change unblocked me for testing as now from test method 
> i can easily invoke a setup call to do flag.Parse() as Jan Mercl pointed 
> out.
>
> I would also recommend that you create a new FlagSet object
> (https://golang.org/pkg/flag/#NewFlagSet) and use that to write more
> testable applications. So, for example:
>
> func setupFlagsAndParse(args []string) {
> fs := flag.NewFlagSet(..)
> # setup the flag and options as usual
> fs.Parse(args)
> ...
> }
>
> Then, you call this function from main() as
> setupFlagsAndParse(os.Args[1:]) or your tests with any slice of
> strings that you may want to test.
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/eb176cd2-8b86-4402-9608-7f92cde3d12fn%40googlegroups.com.

Reply via email to