本文部分内容借鉴于其他blog,但未找到源头,在此基础上做了一层封装和外部调用例子,请各位指正

package myjson

import (
	"bytes"
	"encoding/json"
	"fmt"
	"log"
	"os"
	"regexp"

	simplejson "github.com/bitly/go-simplejson"
)

const configFileSizeLimit = 10 << 20

type Config struct {
	JsonItems  *simplejson.Json
}

func (this *Config) LoadConfig(path string) {

	config_file, err := os.Open(path)
	if err != nil {
		fmt.Println("Failed to open config file '%s': %s\n", path, err)
		return
	}

	fi, _ := config_file.Stat()
	if size := fi.Size(); size > (configFileSizeLimit) {
		fmt.Println("config file (%q) size exceeds reasonable limit (%d) - aborting", path, size)
		return // REVU: shouldn't this return an error, then?
	}

	if fi.Size() == 0 {
		fmt.Println("config file (%q) is empty, skipping", path)
		return
	}

	buffer := make([]byte, fi.Size())
	_, err = config_file.Read(buffer)
	//emit("\n %s\n", buffer)

	buffer, err = StripComments(buffer) //去掉注释
	if err != nil {
		fmt.Println("Failed to strip comments from json: %s\n", err)
		return
	}

	buffer = []byte(os.ExpandEnv(string(buffer))) //特殊

	this.JsonItems, err = simplejson.NewJson([]byte(buffer))

	if err != nil {
		fmt.Printf("%v\n", err)
		return
	}
}

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
}

var (
	ServerConfig Config
)

/*
读配置
*/
func init() {
	ServerConfig.LoadConfig("config.json")
}

上述封装后,即可在其他模块中调用

appid := myjson.ServerConfig.JsonItems.Get("AppId").MustInt()

 

Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐