Binding Properties
Bind raw configuration values into typed Go structs.
Binding turns runtime settings into regular Go values. Define a struct, mark
each field with a property tag, and bind it from a prefix.
type DatabaseProperties struct {
Host string `property:"host,default='localhost'"`
Port int `property:"port,default=5432"`
Username string `property:"username,optional"`
Password string `property:"password,optional"`
Timeout float64 `property:"timeout,default=30.0"`
}var database DatabaseProperties
binder := config.NewDefaultPropertyBinder(env.PropertySources())
if err := binder.Bind("database", &database); err != nil {
return err
}Required values
Fields are required by default. If a field is missing and has no default value, binding returns an error.
type MailProperties struct {
Host string `property:"host"`
Port int `property:"port,default=587"`
}This keeps startup honest: if mail.host is required, the application fails
before the missing configuration causes a later runtime problem.
Optional values
Use optional when the application can continue without a value.
type MailProperties struct {
Username string `property:"username,optional"`
Password string `property:"password,optional"`
}Defaults
Use default for values that should be present even when no property source
defines them.
type ServerProperties struct {
Port int `property:"port,default=8080"`
AllowedMethods []string `property:"allowedMethods,default=['GET','POST']"`
AllowCredentials bool `property:"allowCredentials,default=false"`
}Defaults are converted to the target field type by the binder.
Nested structs
Nested structs keep related settings close to each other and follow the same dot-separated property names.
type ServerProperties struct {
Port int `property:"port,default=8080"`
TLS TLSConfig `property:"tls"`
}
type TLSConfig struct {
Enabled bool `property:"enabled,default=false"`
CertFile string `property:"certFile,optional"`
KeyFile string `property:"keyFile,optional"`
}server:
port: 8443
tls:
enabled: true
certFile: cert.pem
keyFile: key.pemBinding server fills both ServerProperties and the nested TLSConfig.
Slices and maps
The binder can bind slices and maps from direct values or indexed/nested properties.
type ServiceProperties struct {
Ports []int `property:"ports,default=['8080','9090']"`
Labels map[string]string `property:"labels"`
}service:
labels:
env: prod
team: platform