Using A Common Config File
January 7, 2015

Using A Common Config File

Posted on January 7, 2015

While programming with Go, I found out it was easy to store my configurations in a json file. Go’s unmarshaller makes it convenient to tranform it into a struct. Define a go struct then unmarshal the byte array you get from the io reader. This makes it easy to set the database credentials.

// cfg.json
{
   "appname" : "gongfu",
   "http_port" : "",
   "server" : "localhost",
   "db_server" : "localhost",
   "db_name" : "gongfu",
   "db_user" : "gongfu",
   "db_password" : "kungfupanda"
}
// cfg.go (Go)

type JsonCfg struct {
  Appname     string
  Http_port   string
  Server      string
  Db_server   string
  Db_name     string
  Db_user     string
  Db_password string
}

func (cfg *JsonCfg) ConfigFrom(path string) (err error) {
  content, err := ioutil.ReadFile(path)
  if err != nil {
     return
  }
  err = json.Unmarshal(content, &cfg)
  if err != nil {
    log.Printf("bad json", err)
  }
  return
}

var conf JsonCfg

  // in main()
  ...
  err := conf.ConfigFrom('../cfg.json')
  ...

To manage the Postgres database, I wrote some Grunt tasks to dump or re-create the tables. I realized I need the same creditential in json config file. That was easy for Grunt, I just need to read in the same json file.

// Gruntfile.js (Javascript)
module.exports = function(grunt) {
  grunt.initConfig({

    cfg: grunt.file.readJSON('cfg.json'),
    ...

Lastly, I looked at the bash script I used to configure virtual environment and install Postgres. This script will create database with the same username and password. So now, I’ve condensed all my configuration into one file with three different methods to reading cfg.json.

// ubuntu-13.10-64-install.sh (Bash)
jsonval () {
    temp=`echo $jsonval_src | sed 's/\\\\\//\//g' | sed 's/[{}]//g' | awk -v k="text" '{n=split($0,a,","); for (i=1; i<=n; i++) print a[i]}' | sed 's/\"\:\"/\|/g' | sed 's/[\,]/ /g' | sed 's/\"//g' | grep -w $1 | cut -d":" -f2| sed -e 's/^ *//g' -e 's/ *$//g'`
    echo ${temp##*|}
}

jsonval_src=`cat ../cfg.json`

APP_DB_NAME=`jsonval db_name`
APP_DB_USER=`jsonval db_user`
APP_DB_PASS=`jsonval db_password`

You can see this in use in my Gongfu repo. https://github.com/kyledinh/gongfu