Go 用JSON加载表格数据

支持热重载reload,但会有一些问题,下面注释有写

package table

import (
    "runtime/debug"
)

//IntArray int类型数组
type IntArray []int

//FloatArray Float32类型数组
type FloatArray []float32

//StringArray string类型数组
type StringArray []string

type iTable interface {
    load() error
    reload() error
}

var (
    tableList []iTable

    //MFCity 表格
    MFCity = &MFCityTable{file: "../data/mfcity.json"}

    //CityBattleCreature 表格
    CityBattleCreature = &CityBattleCreatureTable{file: "../data/cityBattleCreature.json"}
)

func init() {
    tableList = []iTable{
        MFCity,
        CityBattleCreature,
    }
}

//Load 加载所有表格
func Load() {
    for _, v := range tableList {
        if e := v.load(); nil != e {
            panic(e.Error())
        }
    }
}

//Reload 重新加载所有表格
//说明:
//1、Reload的表不会减少条数,比如A表原来有100条,然后给改成99条,Reload完还是100条
//2、Reload不会改变数组长度,只能改变值,[1,2,3]然后表改成[2,2],Reload后实际是[2,2,3]
func Reload() {
    //中间处理不可预料得错误一定要恢复回来
    defer func() {
        if err := recover(); nil != err {
            log.Error("[Table.Reload] %s", debug.Stack())
        }
    }()

    for _, v := range tableList {
        if e := v.reload(); nil != e {
            log.Error(e.Error())
        }
    }
}


//DeepCopy 深拷贝
//要传入两个指针,不要传值
func DeepCopy(dst, src interface{}) error {
    var buf bytes.Buffer
    if err := gob.NewEncoder(&buf).Encode(src); err != nil {
        return err
    }
    return gob.NewDecoder(bytes.NewBuffer(buf.Bytes())).Decode(dst)
}

表格代码

package table

import (
    "runtime/debug"
)

//MFCityData 单个数据
type MFCityData struct {
    ID         int        `json:"id"`
    City       int        `json:"city"`
    Lv         IntArray   `json:"lv"`
    TaskCommon []IntArray `json:"taskCommon"`
}

//MFCityTable 表格
type MFCityTable struct {
    file    string
    DataMap map[int]MFCityData
}

//load 加载
func (table *MFCityTable) load() error {
    if nil == table.DataMap {
        table.DataMap = make(map[int]MFCityData)
    }

    temp := make([]MFCityData, 0)
    if err := util.LoadJSONConfig(table.file, &temp); nil != err {
        return err
    }

    for _, v := range temp {
        table.DataMap[v.ID] = v
    }

    return nil
}

//reload 重新表格
//重新加载不会不做减量,只做增量和改变
func (table *MFCityTable) reload() error {

    //中间处理不可预料得错误一定要恢复回来
    defer func() {
        if err := recover(); nil != err {
            log.Error("[MFCityTable.reload] %s", debug.Stack())
        }
    }()

    temp := make([]MFCityData, 0)
    if err := util.LoadJSONConfig(table.file, &temp); nil != err {
        return err
    }

    for _, v := range temp {
        //已有的要修改值,新增得直接增加
        if data, ok := table.DataMap[v.ID]; ok {
            DeepCopy(&data, &v)
        } else {
            table.DataMap[v.ID] = v
        }
    }

    return nil
}

//GetByID 根据ID查找
func (table *MFCityTable) GetByID(id int) (*MFCityData, bool) {
    v, ok := table.DataMap[id]
    return &v, ok
}
原文地址:https://www.cnblogs.com/mrblue/p/8969195.html