Skip to content

Instantly share code, notes, and snippets.

@linux-china
Last active April 10, 2024 05:13
Show Gist options
  • Save linux-china/b584183c374860019cf4d8b295616d88 to your computer and use it in GitHub Desktop.
Save linux-china/b584183c374860019cf4d8b295616d88 to your computer and use it in GitHub Desktop.
Replace place holders in Golang Viper
// after viper read config, replace all placeholders with values
func ReplacePlaceHolders() {
r, _ := regexp.Compile("\\${[a-zA-Z0-9.: _]+}")
replacer := func(placeHolder []byte) []byte {
name := string(placeHolder)
name = name[2 : len(name)-1]
index := strings.Index(name, ":")
if index != -1 {
defaultValue := name[index+1:]
name = name[0:index]
value := viper.GetString(name)
if value == "" {
value = defaultValue
}
return []byte(value)
} else {
return []byte(viper.GetString(name))
}
}
for _, k := range viper.AllKeys() {
value := viper.GetString(k)
if strings.Contains(value, "${") && strings.Contains(value, "}") {
newValue := r.ReplaceAllFunc([]byte(value), replacer)
viper.Set(k, string(newValue))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment