一. 概述
配置文件(Configuration File,CF)是一种文本文档,为计算机系统或程序配置参数和初始设置。传统的配置文件就是文本行,在 Unix 系统中随处可见,通常使用 .conf,.config,.cfg 作为后缀,并逐步形成了 key = value 的配置习惯。在 Windows 系统中添加了对 section 支持,通常用 .ini 作为后缀。面向对象语言的兴起,程序员需要直接将文本反序列化成内存对象作为配置,逐步提出了一些新的配置文件格式,包括 JSON,YAML,TOML 等。
二. 任务
配置文件我们编写如下:
# possible values : production, development
app_mode = development
[paths]
# Path to where grafana can store temp files, sessions, and the sqlite3 db (if that is used)
data = /home/git/grafana
[server]
# Protocol (http or https)
protocol = http
# The http port to use
http_port = 9999
# Redirect to correct domain if host header does not match domain
# Prevents DNS rebinding attacks
enforce_domain = false
三. 程序设计
用map的键值对形式来定义configuration,用comment来定义注释的格式
type configuration map[string]string
var comment byte
Init函数根据不同的操作系统确定注释的格式
func Init() {
sys := runtime.GOOS
if sys == "linux" {
comment = '#'
}
if sys == "windows" {
comment = ';'
}
}
Getconf根据文件名读取配置文件,返回configuration。具体实现是将文件打开并读入到缓冲区,然后每次读取一行的内容。如果是空行,注释行,[ ]定义的section行则忽略,否则将其根据“=”拆分为key和value并添加到要返回的configuration中。
func GetConf(filename string) (configuration, error) {
conf := make(configuration)
var returnError error
file, err := os.Open(filename)
if err != nil {
returnError = errors.New("Failed to open file")
return conf, returnError
}
defer file.Close()
buffer := bufio.NewReader(file)
//ifBreak := false
for {
line, err := buffer.ReadString('\n')
if err == io.EOF {
break
} else if err != nil {
returnError = errors.New("error in read")
break
}
if line == "" {
continue
} else if line[0] == comment {
continue
} else if line[0] == '[' && line[len(line)-2] == ']' {
continue
} else {
var key string
var value string
for i := 0; i < len(line); i++ {
if line[i] == '=' {
key = line[:i-1]
value = line[i+2 : len(line)-1]
break
}
}
conf[key] = value
}
}
return conf, returnError
}
PrintConf函数利用for和range打印出configuration中的每一对键值对
func PrintConf(conf configuration) {
for key, value := range conf {
fmt.Printf("key: %s value: %s\n", key, value)
}
}
定义Mylistener为实现Listener接口的结构体,其中包含一个函数类型为ListenFunc的函数,将Mylisten函数实现为真正的监听函数,使用时将其作为参数初始化Mylistener结构体。
type Listener interface {
listen(inifile string)
}
type ListenFunc func(string)
type Mylistener struct {
F ListenFunc
}
func (methods Mylistener) listen(infile string) {
methods.F(infile)
}
func Mylisten(filename string) {
newConf, err := GetConf(filename)
if err != nil {
os.Exit(1)
}
for key, value := range newConf {
if _, ok := testconf[key]; !ok || testconf[key] != value {
testconf = newConf
fmt.Println("file has been changed")
PrintConf(testconf)
break
}
}
return
}
有了上面这些函数,Watch函数基本就可以直接调用它们来简单实现了,首先将配置文件读取到全局变量testconf中,然后在for循环中持续调用listren函数来监听配置文件是否更改。
func Watch(filename string, listener Listener) (configuration, error) {
var err error
testconf, err = GetConf(filename)
if err != nil {
return nil, err
}
PrintConf(testconf)
for {
listener.listen(filename)
}
return testconf, nil
}
四. 编译运行
执行go install github.com/github-user/readConf,将其编译成一个包,然后在main文件夹下的main函数中调用这个包。main函数如下:
package main
import (
readconf "github.com/github-user/readConf"
)
func main() {
l := readconf.Mylistener{readconf.Mylisten}
readconf.Watch("../readConf/conf.ini", l)
}
然后将main.go文件编译运行即可
五. 功能测试
编译运行main.go,输出如下:
将配置文件中http_port的值从9999改为9998,程序立即输出:
六. 单元测试
编写测试文件如下:
package readconf
import (
"os"
"testing"
)
func Test(t *testing.T) {
expected := make(configuration)
expected["app_mode"] = "development"
expected["data"] = "/home/git/grafana"
expected["protocol"] = "http"
expected["http_port"] = "9999"
expected["enforce_domain"] = "true"
testconf, err := GetConf("conf.ini")
if err != nil {
os.Exit(1)
}
for key, value := range expected {
if value != testconf[key] {
t.Errorf("expect %s but got %s", value, testconf[key])
}
}
}
执行go test,输出如下: