Last active
April 10, 2024 05:13
-
-
Save linux-china/b584183c374860019cf4d8b295616d88 to your computer and use it in GitHub Desktop.
Replace place holders in Golang Viper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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