Golang Config File Best Practise

In this article, We will show you how to configure the config file in the Go project.

Image for post
Image for post
Image for post
Image for post
{"DB_USERNAME": "test","DB_PASSWORD": "test","DB_PORT": "3306","DB_HOST": "127.0.0.1","DB_NAME": "test"}
{"DB_USERNAME": "prod_test","DB_PASSWORD": "prod_test","DB_PORT": "3306","DB_HOST": "127.0.0.1","DB_NAME": "prod_test"}
package mainimport ("github.com/tkanos/gonfig""fmt")type Configuration struct {  DB_USERNAME string  DB_PASSWORD string  DB_PORT     string  DB_HOST     string  DB_NAME     string}func GetConfig(params ...string) Configuration {  configuration := Configuration{}  env := "dev"  if len(params) > 0 {   env = params[0]  }  fileName := fmt.Sprintf("./%s_config.json", env)  gonfig.GetConf(fileName, &configuration)  return configuration}
package mainimport "fmt"func main() {fmt.Println("Dev Configuration\n")configuration := GetConfig()fmt.Println(configuration.DB_USERNAME)fmt.Println(configuration.DB_PASSWORD)fmt.Println(configuration.DB_PORT)fmt.Println(configuration.DB_NAME)fmt.Println("\nProd Configuration\n")configuration = GetConfig("prod")fmt.Println(configuration.DB_USERNAME)fmt.Println(configuration.DB_PASSWORD)fmt.Println(configuration.DB_PORT)fmt.Println(configuration.DB_NAME)}
Dev Configurationtest
test
test
3306
testProd Configurationprod_test
prod_test
3306
prod_test

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store