package models
import (
"bytes"
"encoding/json"
"log"
"os"
"regexp"
"fuckGFWClient/conf"
)
const configFileSizeLimit = 10 << 20
//有了`json:network`这种注释,后面json解析就可以把相应的数据塞到对应的结构里面来
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格式数据
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
}
网友评论