Go JSON config file

Seems there’s no standard or official way to load configuration files in Go. There are libraries out there, but if you’re just looking for something simple, you’d just read a JSON file into your application.

config/configuration.go

package config

import (
	"encoding/json"
	"log"
	"os"
)

type Configuration struct {
	Email    Email    `json:"email"`
	Services []string `json:"services"`
}

func LoadConfig() *Configuration {
	file, err := os.Open("conf.json")
	if err != nil {
		log.Fatal(err)
	}
	defer file.Close()
	decoder := json.NewDecoder(file)
	config := &Configuration{}
	err = decoder.Decode(config)
	if err != nil {
		log.Fatal(err)
	}
	return config
}

config/email.go

package config

type Email struct {
	From       string   `json:"from"`
	Subject    string   `json:"subject"`
	Recipients []string `json:"recipients"`
}

conf.json

{
    "email": {
        "from": "test@example.com",
        "subject": "Email Subject",
        "recipients": [
            "test1@example.com",
            "test2@example.com"
        ]
    },
    "services": [
        "First Service",
        "Second Service",
        "Third Service"
    ]
}

main.go

package main

import (
	"fmt"

	"github.com/jtenos/hellogo/config"
)

var conf *config.Configuration

func main() {
	conf = config.LoadConfig()

	fmt.Println("Email:")
	fmt.Printf("  From: %s\n", conf.Email.From)
	fmt.Printf("  Subject: %s\n", conf.Email.Subject)
	for _, rec := range conf.Email.Recipients {
		fmt.Printf("  Recipient: %s\n", rec)
	}

	fmt.Println("Services:")
	for _, svc := range conf.Services {
		fmt.Printf("  %s\n", svc)
	}
}

Leave a Reply

Your email address will not be published.