Go 用JSON加載表格數據

支持熱重載reload,但會有一些問題,下面註釋有寫json

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 從新加載全部表格
//說明:
//一、Reload的表不會減小條數,好比A表原來有100條,而後給改爲99條,Reload完仍是100條
//二、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
}
相關文章
相關標籤/搜索