golang 讀取json文件

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
}
?著作權(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ù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容