properties icon indicating copy to clipboard operation
properties copied to clipboard

Ability Decode to Multiple structs

Open BoraBak opened this issue 3 years ago • 5 comments

In case the properties file has a logical division of the configurations, I'd like to decode to several dedicated structs.

For example: Given the following config.properties file

app.port=3000
db.host=127.0.0.1
db.port=8000
db.username=username123
db.password=password123
pglistener.min_reconn=10 * time.Second
pglistener.max_reconn=1 * time.Minute
...
...

I'd like to decode to the following structs:

type Config struct {
	AppPort string `properties:"app.port,default=3000"`
}

type DBConfig struct {
	Host          string  `properties:"db.host,default=127.0.0.1"`
	Port           int       `properties:"db.port,default=5432"`
	Username string `properties:"db.username"`
	Password  string `properties:"db.password"`
}


type PGListener struct {
	MinReconnectInterval time.Duration `properties:"pglistener.min_reconn"`
	MaxReconnectInterval time.Duration `properties:"pglistener.max_reconn"`
}

BoraBak avatar Jun 06 '21 07:06 BoraBak

Does it work if you embed them into one large struct?

magiconair avatar Jun 06 '21 09:06 magiconair

@magiconair not sure what you meant:

Option-1 doesn't work.

type Config struct {
	AppPort     string `properties:"app.port,default=3000"`
        DBConfig   *DBConfig
        PGListener *PGListener
}

Option-2 works, but it's not my desired solution/architecture.

type Config struct {
	AppPort     string `properties:"app.port,default=3000"`
	Host          string  `properties:"db.host,default=127.0.0.1"`
	Port           int       `properties:"db.port,default=5432"`
	Username string `properties:"db.username"`
	Password  string `properties:"db.password"`
	MinReconnectInterval time.Duration `properties:"pglistener.min_reconn"`
	MaxReconnectInterval time.Duration `properties:"pglistener.max_reconn"`
}

BoraBak avatar Jun 06 '21 09:06 BoraBak

Does it work if you rename DBConfig to DB in option 1?

magiconair avatar Jun 06 '21 09:06 magiconair

@magiconair nope.

BoraBak avatar Jun 06 '21 11:06 BoraBak

maybe embedding mean this, move the prefix in tag of embedded struct to tag of parent struct:

type Config struct {
	AppPort string `properties:"app.port,default=3000"`
	DBConfig `properties:"db"`
	PGListener `properties:"pglistener"`
}

type DBConfig struct {
	Host          string  `properties:"host,default=127.0.0.1"`
	Port           int       `properties:"port,default=5432"`
	Username string `properties:"username"`
	Password  string `properties:"password"`
}

type PGListener struct {
	MinReconnectInterval time.Duration `properties:"min_reconn"`
	MaxReconnectInterval time.Duration `properties:"max_reconn"`
}

KangKangTao avatar Jun 17 '23 12:06 KangKangTao