Dependency inject or import application config?

Hi,

I am currently storing application config in a struct (created from .env file at application boot) and dependency inject only the relevant ones where they are needed. See a dumb example below please.

// Assume that the cnf is a multidimensional struct in config.go.

// cmd/main.go
whoAreYou(cnf.App.Name, cnf.Env, cnf.Build.Ver)

// internal/hello.go
func whoAreYou(name, env string, ver int) string {
   return fmt.Sprintf("%s %s %d", name, env, ver)
}

What I was thinking is that, is this really a Go-ish way of working? I mean is it not better to just store whole config in a variable and access/import it where ever it is needed just like we normally use log package? The example then changes as below.

// Assume that the Cnf is a multidimensional struct stored as var in config.go.

// cmd/main.go
whoAreYou()

// internal/hello.go
inport "config"

func whoAreYou() string {
   return fmt.Sprintf("%s %s %d", config.Cnf.App.Name, config.Cnf.Env, config.Cnf.Build.Ver)
}

Thanks

Technically, being into a package you can consider the technique idiomatic but practically if your package is useful only for this application is more clean and easy to use a global variable to store configuration.

I wouldn’t use global configuration, it limits testing, especially parallel testing.

I wouldn’t use global configuration, it limits testing, especially parallel testing.

Assuming that the app is using 12 Factor rule for env vars and if the tests are your concern, you can always manually set env var(s) in your test and let your test case expect whatever it needs to. So I don’t think the tests would be enough reason to block implementing global config which is purely application specific thing.

it is true for app version, name kind of variables but not true for library/service dependencies. I assume OP wants to know how to use these dependencies within a function or a package.

and dependency inject only the relevant ones where they are needed

1 Like

The config contains application specific vars so they are only relevant to the application itself. All the go files in the application are not shared across any other external app or package. It is like, you have money in your pocket and that money only for you to spend. No one is meant to put their hand into your pocket unless there is a pick-pocket which is a bug

I’ll stick with the current implementation which doesn’t make use of global var for config after reading some posts and this.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.