spf13/cobra

Question about structure and initialization

jsumners opened this issue · 1 comments

There are a few similar issues about the boilerplate code Cobra provides and the examples in the readme, but my question is more specifically about how Cobra expects initialization to work.

I have an experiment at https://github.com/jsumners/go-experiments/tree/9eec03a1b5045f2df4b0f4d41dbc8a3a21a41cf4/cli-cobra wherein I have put together a pattern that makes sense to me. It:

  1. Utilizes a persistent flag to specify a configuration file
  2. Utilizes the PersistentPreRunE hook to load any configuration file specified by the flag
  3. Shows that the configuration is available to subcommands

That last point is true because https://github.com/jsumners/go-experiments/blob/9eec03a1b5045f2df4b0f4d41dbc8a3a21a41cf4/cli-cobra/main.go#L16 initializes the configuration to a zero-like value, and the Cobra hook merely adjusts values on that object.

The issue I'm having difficulty determining a solution for is shown in commit jsumners/go-experiments@f48cf27. In that commit, I have refactored things such that the "auth" command utilizes an http client that is supposed to be initialized by the same Cobra initialization as the configuration. However, this doesn't work because the closure over the http client is bound to a nil pointer. I can't initialize the http client in the same way as the configuration because the http client depends on information from the configuration object.

In short:

I need Cobra to process the --conf-file switch so that the initConfig function can read data from the specified file. And I need data from the conf file to initialize the http client. But I'm not seeing a way to utilize Cobra's initialization hooks to accomplish this goal.

Any tips would be greatly appreciated.

For anyone interested in this issue, I solved it by:

I would like a better solution, but this will do for now.