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
file: $GOPATH/src/github.com/thewhitetulip/Tasks/config.json
file: $GOPATH/src/github.com/thewhitetulip/Tasks/main.go
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
Links
Last updated