2017-12-12 21:51:25 +07:00
## Introduction
2017-12-12 22:33:47 +07:00
**config** is a simple golang library and designed to read configurations from JSON, Yaml files, environment variables and command line. **config** depends on [go-yaml ](https://github.com/go-yaml/yaml ) to anlayze Yaml file and uses built-in golang library to handle JSON file.
2017-12-12 21:51:25 +07:00
## Installation
1. Install [Yaml ](https://github.com/go-yaml/yaml ) library first:
```
go get gopkg.in/yaml.v2
```
2017-12-12 22:18:55 +07:00
2. Install **config** library:
2017-12-12 21:51:25 +07:00
```
go get github.com/eschao/config
```
## Usage
2017-12-12 22:33:47 +07:00
#### 1. Defines **default** values
2017-12-12 22:18:55 +07:00
**config** library supports defining a default value for structure members by using **default** keyword in structure tags
2017-12-12 22:33:47 +07:00
```golang
type Log struct {
Path string `default:"/var/logs"`
Level string `default:"debug"`
}
```
After that, calls ```config.ParseDefault(interface{})``` to set it on structure instance, example codes as the below:
```golang
logConfig := Log{}
config.ParseDefault(& logConfig)
```
#### 2. Reads configurations from JSON file
Like analyzing JSON object from file, reading configurations from JSON file is also simple:
2017-12-12 22:18:55 +07:00
```golang
type Database struct {
2017-12-12 22:33:47 +07:00
Host string `json:"host"`
Port int `json:"port"`
Username string `json:"username" default:"admin"`
Password string `json:"password" default:"admin"`
Log Log `json:"log"`
2017-12-12 22:18:55 +07:00
}
```
2017-12-12 22:33:47 +07:00
Parsing configurations from JSON:
2017-12-12 22:18:55 +07:00
```golang
dbConfig := Database{}
2017-12-12 22:33:47 +07:00
config.ParseConfigFile(& dbConfig, "config.json")
2017-12-12 22:18:55 +07:00
```