package utils
import (
"bufio"
"io"
"os"
"strings"
//"fmt"
)
const mid = "=="
type Config struct {
m map[string]string
s string
}
//config example as follow
/*[app]
*#應用運行模式,我們采用了gin框架,目前支持debug/release/test三種
*mode=debug
*#應用的名稱,以后擴展,用做應用標識,便於分布式計算
*name=xxx
*#應用部署的訪問協議,支持http/https兩種
*protocal=http
*#應用域名
*domain=localhost:888
*#靜態資源所在的服務器地址,便於動靜態分離
*asset=localhost:888/asset
*#請求contextpath
*ctxpath=
*#服務器綁定的地址
*addr=localhost
*#端口
*port=8888
*[session]
*#sessionID標識字符串,對標PHP的SESSIONID,java的JSESSIONID
*name=restgo_session_id
*#session過期時間以秒為單位,0表示訪問結束時過期
*timelive=3600
*/
//Unix Style Parse Config File
func(c *Config) Init(path string){
c.m = make(map[string]string)
f,err := os.Open(path) //try to open file
if err != nil {
panic(err)
}
defer f.Close()
r := bufio.NewReader(f)
for {
b, _, err := r.ReadLine()
if err != nil {
if err == io.EOF{
break
}
panic(err)
}
s := strings.TrimSpace(string(b))
if strings.Index(s,"#") == 0 {
continue
}
n1 := strings.Index(s,"[")
n2 := strings.LastIndex(s,"]")
if n1 > -1 && n2 > -1 && n2 > n1+1 {
c.s = strings.TrimSpace(s[n1+1:n2])
continue
}
if len(c.s) == 0 {
continue
}
i := strings.Index(s,"=")
if i < 0{
continue
}
key := strings.TrimSpace(s[:i])
if len(key) == 0{
continue
}
value := strings.TrimSpace(s[i+1:])
if len(value) == 0 {
continue
}
//mark
pos := strings.Index(value,"\t#")
if pos > -1 {
value = value[0:pos]
}
pos = strings.Index(value,"#")
if pos > -1 {
value = value[0:pos]
}
pos = strings.Index(value,"\t//")
if pos > -1 {
value = value[0:pos]
}
pos = strings.Index(value,"//")
if pos > -1 {
value = value[0:pos]
}
if len(value) == 0{
continue
}
k := c.s + mid + key
c.m[k] = strings.TrimSpace(value)
}
}
func (c *Config)Read(node,key string) string {
key = node + mid + key
v,err := c.m[key]
if !err {
return ""
}
return v
}