paulgorman.org

2017-11-13 16:40:18 -0500 EST

Read JSON config file in Golang

How do we read a JSON configuration file for our Go program?

This is the config file:

{
	"Db": {
		"Host": "localhost",
		"User": "maintcall",
		"Password": "vEryst0ng-paS5swordheR3",
		"Database":  "maintcall"
	},
	"Listen": {
		"Address": "*",
		"Port": "8000"
	},
	"OutboundCall": {
		"CallerID": "\"HT MAINTENANCE\" <+12483522010>",
		"Retries": 3,
		"SpoolPath": "/var/spool/asterisk/outgoing/"
	},
	"VmRoot": "/var/spool/asterisk/voicemail/default/"
}

And here’s the Go program that reads it:

package main

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

type Configuration struct {
	Db struct {
		Host     string
		User     string
		Password string
		Database string
	}
	Listen struct {
		Address string
		Port    string
	}
	OutboundCall struct {
		CallerID  string
		Retries   int
		SpoolPath string
	}
	VmRoot string
}

func main() {
	c := flag.String("c", "/etc/my-daemon.conf", "Specify the configuration file.")
	flag.Parse()
	file, err := os.Open(*c)
	if err != nil {
		log.Fatal("can't open config file: ", err)
	}
	defer file.Close()
	decoder := json.NewDecoder(file)
	Config := Configuration{}
	err = decoder.Decode(&Config)
	if err != nil {
		log.Fatal("can't decode config JSON: ", err)
	}
	log.Println(Config.Db.Host)
}

#golang

⬅ Older Post Newer Post ➡