Description
This example demonstrates how you could use the jsoncfgo config file reader.
jsoncfgo Features
jsoncfgo can handle the following data types in the .json configuration file that it reads:
- bool
- int
- int64
- string
- []string
- []int64
You can also call the Validate function to validate attempts to read non-existent variables.
Golang Features
This golang code sample demonstrates the following go language features:
- Simple printing using fmt package
Code Example
In this code example we demonstrate how to use jsoncfgo convenience functions to read a simple json-based configuration file.
package main
import (
"fmt"
"time"
"log"
"github.com/l3x/jsoncfgo"
)
func main() {
cfg := jsoncfgo.Load("/Users/lex/dev/go/data/jsoncfgo/simple-config.json")
host := cfg.String("host")
fmt.Printf("host: %v\n", host)
bogusHost := cfg.String("bogusHost", "default_host_name")
fmt.Printf("host: %v\n\n", bogusHost)
port := cfg.Int("port")
fmt.Printf("port: %v\n", port)
bogusPort := cfg.Int("bogusPort", 9000)
fmt.Printf("bogusPort: %v\n\n", bogusPort)
bigNumber := cfg.Int64("bignNumber")
fmt.Printf("bigNumber: %v\n", bigNumber)
bogusBigNumber := cfg.Int64("bogusBigNumber", 9000000000000000000)
fmt.Printf("bogusBigNumber: %v\n\n", bogusBigNumber)
active := cfg.Bool("active")
fmt.Printf("active: %v\n", active)
bogusFalseActive := cfg.Bool("bogusFalseActive", false)
fmt.Printf("bogusFalseActive: %v\n", bogusFalseActive)
bogusTrueActive := cfg.Bool("bogusTrueActive", true)
fmt.Printf("bogusTrueActive: %v\n\n", bogusTrueActive)
appList := cfg.List("appList")
fmt.Printf("appList: %v\n", appList)
bogusAppList := cfg.List("bogusAppList", []string{"app1", "app2", "app3"})
fmt.Printf("bogusAppList: %v\n\n", bogusAppList)
numbers := cfg.IntList("numbers")
fmt.Printf("numbers: %v\n", numbers)
bogusSettings := cfg.IntList("bogusSettings", []int64{1, 2, 3})
fmt.Printf("bogusAppList: %v\n\n", bogusSettings)
}
Notes
You will need to change the configPath to point to a the configuration file on your computer.
Any read errors are handled for us; Errors are logged to standard out.
For a more detailed example of how to leverage the more advanced features of jsoncfgo, please see jsoncfgo - Advanced Usage
Install jsconfgo
Install the jsconfgo library as follows:
$ go get github.com/l3x/jsoncfgo
Input
example_simple.json
{
"host": "localhost",
"port": 9000,
"active": true,
"appList": ["myapp", "sharedapp"]
}
Output
host: localhost
host: default_host_name
port: 5432
bogusPort: 9000
bigNumber: 999999999999999
bogusBigNumber: 9000000000000000000
active: true
bogusFalseActive: false
bogusTrueActive: true
appList: [myapp sharedapp]
bogusAppList: [app1 app2 app3]
Process finished with exit code 1