golang学習:jsonファイルの読み取りと解析


本文の一部の内容は他のblogに鑑みて、しかしソースが見つからないで、この基礎の上で1層のパッケージと外部の呼び出しの例をして、各位に指摘してもらいます
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
", 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("
%s
", buffer) buffer, err = StripComments(buffer) // if err != nil { fmt.Println("Failed to strip comments from json: %s
", err) return } buffer = []byte(os.ExpandEnv(string(buffer))) // this.JsonItems, err = simplejson.NewJson([]byte(buffer)) if err != nil { fmt.Printf("%v
", err) return } } func StripComments(data []byte) ([]byte, error) { data = bytes.Replace(data, []byte("\r"), []byte(""), 0) // Windows lines := bytes.Split(data, []byte("
")) //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("
")), nil } var ( ServerConfig Config ) /* */ func init() { ServerConfig.LoadConfig("config.json") }

上記パッケージ化後、他のモジュールで呼び出すことができます
appid := myjson.ServerConfig.JsonItems.Get("AppId").MustInt()