package models
import (
"bytes"
"encoding/json"
"log"
"os"
"regexp"
"fuckGFWClient/conf"
)
const configFileSizeLimit = 10 << 20
//有了`json:network`這種注釋,后面json解析就可以把相應(yīng)的數(shù)據(jù)塞到對應(yīng)的結(jié)構(gòu)里面來
type Config struct {
Server string `json:"server"`
LocalPort int `json:"local_port"`
Server_port string `json:"server_port"`
Password string `json:"password"`
Method string `json:"method"`
TimeOut int `json:"time_out"`
}
func GetConfig() *Config {
config := LoadConfig(conf.CONFIG_PATH)
return config
}
func LoadConfig(path string) *Config {
var config Config
config_file, err := os.Open(path)
if err != nil {
emit("Failed to open config file '%s': %s\n", path, err)
return &config
}
fi, _ := config_file.Stat()
if size := fi.Size(); size > (configFileSizeLimit) {
emit("config file (%q) size exceeds reasonable limit (%d) - aborting", path, size)
return &config // REVU: shouldn't this return an error, then?
}
if fi.Size() == 0 {
emit("config file (%q) is empty, skipping", path)
return &config
}
buffer := make([]byte, fi.Size())
_, err = config_file.Read(buffer)
//emit("\n %s\n", buffer)
buffer, err = StripComments(buffer) //去掉注釋
if err != nil {
emit("Failed to strip comments from json: %s\n", err)
return &config
}
buffer = []byte(os.ExpandEnv(string(buffer))) //特殊
err = json.Unmarshal(buffer, &config) //解析json格式數(shù)據(jù)
if err != nil {
emit("Failed unmarshalling json: %s\n", err)
return &config
}
return &config
}
func StripComments(data []byte) ([]byte, error) {
data = bytes.Replace(data, []byte("\r"), []byte(""), 0) // Windows
lines := bytes.Split(data, []byte("\n")) //split to muli lines
filtered := make([][]byte, 0)
for _, line := range lines {
match, err := regexp.Match(`^\s*#`, line)
if err != nil {
return nil, err
}
if !match {
filtered = append(filtered, line)
}
}
return bytes.Join(filtered, []byte("\n")), nil
}
func emit(msgfmt string, args ...interface{}) {
log.Printf(msgfmt, args...)
}
func ResultConfig(test []map[string]interface{}) (port_password []map[string]interface{}) {
return
}
golang 讀取json文件
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
相關(guān)閱讀更多精彩內(nèi)容
- 首先安裝python環(huán)境,安裝xlrd,可以去python官網(wǎng)下載。安裝的過程可能遇到setup.py insta...
- 前 言 BUFIO 是什么?BUFIO 是用來驅(qū)動 I/O 列內(nèi)的專用時鐘網(wǎng)絡(luò),這個專用的時鐘網(wǎng)絡(luò)獨(dú)立于全局時鐘資...
- 使用大神寫的庫jinzhu/configor 1.安裝 go get github.com/jinzhu/conf...
- 前兩天零零碎碎看完了golang的基礎(chǔ),想著找個小項目練練手,可是出現(xiàn)了一個十分棘手的問題我要做的東西是網(wǎng)站路徑爆...