Working with Files

JSON and XML are two of the most common ways to transmit data between web applications. We'll use JSON for our configuration file.

For our webapplication we have a set of configuration values like the server port where our application will run. Suppose you are developing your application in $GOPATH and also using it somewhere else, then you can't run them in parallel because both sources use the same port number. Naturally we want a way to parameterize that port number. The parameter or configuration value list may contain more things like database connection information. As of now we will use a config.json file and read the serverPort variable and bind our server on that port.

Our configuration file uses a fixed structure, hence it is simple enough to UnMarshal it to a struct type, we can use some advance concepts to accomodate unstructured JSON files, because that is the whole point of JSON, we can have data in an unstructured format.

NoSQL has been famous lately, they are basically JSON document stores. We have projects like boltdb which store data in a key value pair, ultimately in flat files or in memory.

file: $GOPATH/src/github.com/thewhitetulip/Tasks/config/config.go

package config

import (
    "encoding/json"
    "io/ioutil"
    "log"
)

// Stores the main configuration for the application
// define a struct object containing
type Configuration struct {
    ServerPort string
}

var err error
var config Configuration

// ReadConfig will read the config.json file to read the parameters
// which will be passed in the config object
func ReadConfig(fileName string) Configuration {
    configFile, err := ioutil.ReadFile(fileName)
    if err != nil {
        log.Fatal("Unable to read log file")
    }
    //log.Print(configFile)
    err = json.Unmarshal(configFile, &config)
    if err != nil {
        log.Print(err)
    }
    return config
}

file: $GOPATH/src/github.com/thewhitetulip/Tasks/config.json

{
    "ServerPort": ":8081"
}

file: $GOPATH/src/github.com/thewhitetulip/Tasks/main.go

values := config.ReadConfig("config.json")

// values is the object now, we can use the
// below statement to access the port name

values.ServerPort

We use the json.Unmarshal to read the JSON file into our structure object. This is a very simple and basic example of parsing JSON files, you can have nested structures of many levels inside the main config object, but that is the features of Go, so long as it can be represented as a JSON document you can use the Unmarshal method to translate the file into an object which you can use in your program.

Homework

  • Alter the config.json file to take the name of the sqlite database as a configuration parameter.

  • Read about the JSON library in godoc

-Previous section -Next section

Last updated