Using JSON Config in Go
In this article, we’re going to see how we can use json files an config for out Go applications.
First of all, we have to define struct, to load our config.
Example,
type Config struct {
Database struct {
Host string `json:"host"`
Password string `json:"password"`
User string `json:"user"`
Port int `json:"port"`
} `json:"database"`
Token string `json:"token"`
}This struct can load, following json
{
"database": {
"host": "localhost",
"password": "12345"
"user": "user",
},
"token": "super_secret_token"
}Now let’s see how we can load this.
Get Sumeet’s stories in your inbox
Join Medium for free to get updates from this writer.
As we know, Go will assign zero values of respective types if value is not given. Hence, we will create an value of our Config type, and add any default values if we want.
In our example, we’re assigning defualt value 5432 for port field.
config := Config{
Database: struct {
Host string `json:"host"`
Password string `json:"password"`
User string `json:"user"`
Port int `json:"port"`
}{
Port: 5432,
},
}Now, we just have to open a file, and decode the content into the struct.
configFile, err := os.Open(homeDir + "/.config/your_config.json")
defer configFile.Close()
if err != nil {
log.Fatal(err)
}
jsonParser := json.NewDecoder(configFile)
jsonParser.Decode(&config)We’re done!
Full code:
type Config struct {
Database struct {
Host string `json:"host"`
Password string `json:"password"`
User string `json:"user"`
Port int `json:"port"`
} `json:"database"`
Token string `json:"token"`
}
func GetConfig() Config {
config := Config{
Database: struct {
Host string `json:"host"`
Password string `json:"password"`
User string `json:"user"`
Port int `json:"port"`
}{
Port: 5432,
},
}
homeDir, err := os.UserHomeDir()
if err != nil {
log.Fatal(err)
}
configFile, err := os.Open(homeDir + "/.config/your_config.json")
defer configFile.Close()
if err != nil {
log.Fatal(err)
}
jsonParser := json.NewDecoder(configFile)
jsonParser.Decode(&config)
return config
}









