jinzhu / configor

Golang Configuration tool that support YAML, JSON, TOML, Shell Environment

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Add support for loading into interface fields which have a *struct{} in them

nickpalmer opened this issue · comments

Describe the feature

Add the ability to load a struct that has an interface element which has a struct assigned to it

Motivation

This would support go style polymorphism, where a portion of the configuration is set before Load() is called.

Consider the following:

type DatabaseProvider interface {
  GetDatabase() *gorm.DB
}
type SqliteDatabase struct {
  File string `env:"SQLITE_DATABASE_FILE"`
  // ...
}
func (s *SqliteDatabase) GetDB() *gorm.DB {
  // ...
}
type PostgresqlDatabase struct {
  Name string `env:"PSQL_DATABASE_NAME"`
  // ...
}
func (p *PostgresqlDatabase) GetDB() *gorm.DB {
  // ...
}
type AppConfig struct {
  DatabaseProvider `anonymous:"true"`
}
func NewAppConfig() (*AppConfig, error) {
  env := os.GetEnvironment("ENVIRONMENT")
  var appConfig *AppConfig
  switch env {
  case "dev":
    appConfig = &AppConfig{ &SqliteDatabase{} }
  default:
    appConfig = &AppConfig{ &PostgresqlDatabase{} }
  }
  return appConfig, configor.New(&configor.Config{}).Load(appConfig)
}

Currently configor will not load the underlying database configuration, but there is no reason that it cannot do so since the value of the interface is a struct.

Related Issues