Go Config File Best Practise

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

Image for post

There are many libraries available such as Viper, GoDotEnv, etc But we are using Gonfig.

We are using following different files one for production env and second for development env.

dev_config.json (Development Environment)

{"DB_USERNAME": "test","DB_PASSWORD": "test","DB_PORT": "3306","DB_HOST": "127.0.0.1","DB_NAME": "test"}

https://gist.github.com/4957fed751fa843d96ab14a677dc7e59

prod_config.json (Production Environment)

{"DB_USERNAME": "prod_test","DB_PASSWORD": "prod_test","DB_PORT": "3306","DB_HOST": "127.0.0.1","DB_NAME": "prod_test"}

https://gist.github.com/1a4acf19065358fc0e0bed5d4756c479

config.go file

package mainimport ("github.com/tkanos/gonfig""fmt")type Configuration struct {DB_USERNAME stringDB_PASSWORD stringDB_PORT     stringDB_HOST     stringDB_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}

https://gist.github.com/0d1195748302be30b6e16543138d3251

Here is main.go file

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)}

https://gist.github.com/8e3e645c95237a026fbdc3093014f41a

Final output:

Dev Configurationtest
test
3306
test
Prod Configurationprod_test
prod_test
3306
prod_test

Try following example code

https://repl.it/@onexlab/goconfig

Written by

We teach & develop for startups

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