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.


package config

import (

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

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


package config

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


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


package main

import (


var conf *config.Configuration

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

	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)

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s