Load configurations
There are different ways to load configurations into your application:
From a file
First, configure your project in a yaml file:
config.dist.yml
port: 80
host: example.com
struct_example:
port: 80
host: example.com
timeout: 5s
threshold: 100
Then, load your configurations into your application:
main.go
package main
import (
// 1
"github.com/justtrackio/gosoline/pkg/cfg"
)
func main() {
// 2
config := cfg.New()
// 3
options := []cfg.Option{
cfg.WithConfigFile("config.dist.yml", "yml"),
}
// 4
if err := config.Option(options...); err != nil {
panic(err)
}
}
Here, you:
- Import the
cfg
package. - Create a new configuration object.
- Load configurations from the file.
- Apply the options.
From a map
main.go
package main
import (
// 1
"github.com/justtrackio/gosoline/pkg/cfg"
)
func main() {
// 2
config := cfg.New()
// 3
options := []cfg.Option{
cfg.WithConfigMap(map[string]interface{}{
"enabled": true,
}),
}
// 4
if err := config.Option(options...); err != nil {
panic(err)
}
}
Here, you:
- Import the
cfg
package. - Create a new configuration object.
- Load configurations from the map.
- Apply the options.
From individual settings
main.go
package main
import (
// 1
"github.com/justtrackio/gosoline/pkg/cfg"
)
func main() {
// 2
config := cfg.New()
// 3
options := []cfg.Option{
cfg.WithConfigSetting("host", "localhost"),
cfg.WithConfigSetting("port", "80"),
}
// 4
if err := config.Option(options...); err != nil {
panic(err)
}
}
Here, you've:
- Import the
cfg
package. - Create a new configuration object.
- Load configurations from settings.
- Apply the options.
From multiple sources
main.go
package main
import (
// 1
"github.com/justtrackio/gosoline/pkg/cfg"
)
func main() {
// 2
config := cfg.New()
// 3
options := []cfg.Option{
cfg.WithConfigFile("config.dist.yml", "yml"),
cfg.WithConfigMap(map[string]interface{}{
"enabled": true,
}),
cfg.WithConfigSetting("foo", "bar"),
}
// 4
if err := config.Option(options...); err != nil {
panic(err)
}
}
Here, you've:
- Import the
cfg
package. - Create a new configuration object.
- Load configurations from multiple sources.
- Apply the options.
Once you've loaded your configurations, you can access them with type-specific getters. For example:
main.go
package main
import (
"fmt"
"github.com/justtrackio/gosoline/pkg/cfg"
)
func main() {
config := cfg.New()
options := []cfg.Option{
cfg.WithConfigFile("config.dist.yml", "yml"),
}
if err := config.Option(options...); err != nil {
panic(err)
}
fmt.Printf("got port: %d\n", config.GetInt("port"))
fmt.Printf("got host: %s\n", config.GetString("host"))
}
Conclusion
In this guide, you've learned multiple ways to load configurations into your app with gosoline.
Check out these resources to learn more about configurations and gosoline: