How to use go:embed to read application properties

1k Views Asked by At

I use viper to load runtime environment specific property files (located under ./configs/*.conf). I am looking to see how I can embed these files in the binary.

Following snippet that loads the files

viper.AddConfigPath("./configs")
viper.SetConfigName("app_dev.conf")
viper.ReadInConfig()

I have tried using the following embed directive

//go:embed configs/*.conf
var resources embed.FS

However getting an error that it cannot load the property files. It works, as expected, if I add the config folder in the same location as the binary.

2

There are 2 best solutions below

2
On

I realized that I can use io.reader to load Viper config

data, _ := _configFile.ReadFile("configs/app_dev.conf")
err = viper.ReadConfig(strings.NewReader(string(data)))
0
On

Here is how an answer to the original question (with file embedding) could look like:

import (
    "bytes"
    "embed"
    "github.com/spf13/viper"
)

//go:embed configs/*.conf
var resources embed.FS

data, err := resources.ReadFile("configs/app_dev.conf")
if err != nil {
    panic(err)
}
err = viper.ReadConfig(bytes.NewReader(data))