package internal import ( "crypto/md5" "encoding/hex" "encoding/json" "fmt" "io" "os" "strings" "sync" "tools/logic/cutil" "github.com/gin-gonic/gin" ) const SPLIT = 100000 const DATA_SOURCE_FILE = "internal.json" type Internal struct { tableName string Index int64 IdList map[string]int64 } type Super struct { sync.Mutex DataSource map[string]*Internal IndexMapping map[string]int64 Split int64 } var dataSource *Super func init() { Load() } func Load() { dataSource = &Super{DataSource: make(map[string]*Internal), IndexMapping: make(map[string]int64)} //load data, err := os.ReadFile(DATA_SOURCE_FILE) if err != nil { fmt.Println("load data file error") return } err = json.Unmarshal(data, &dataSource) if err != nil { fmt.Println("unmarshal data error") return } } func GetInternalId(ctx *gin.Context) { tableName := ctx.Request.Header.Get("tableName") idstr := ctx.Request.Header.Get("ids") ids := strings.Split(idstr, ",") dataSource.Lock() defer dataSource.Unlock() ret, ok := dataSource.DataSource[tableName] if ok { list := ret.IdList add := false for _, id := range ids { _, ok := list[id] if ok { continue } ret.Index++ //新的行 ret.IdList[id] = ret.Index add = true } if add { save() } ctx.JSON(200, buildRet(ids, ret.IdList)) } else { //有新表了 var split = dataSource.Split newIndex := split + SPLIT dataSource.Split = newIndex dataSource.IndexMapping[tableName] = newIndex idmap := Internal{tableName: tableName, IdList: make(map[string]int64)} for _, id := range ids { newIndex++ idmap.IdList[id] = newIndex } idmap.Index = newIndex dataSource.DataSource[tableName] = &idmap save() ctx.JSON(200, buildRet(ids, idmap.IdList)) } } func buildRet(ids []string, IdList map[string]int64) []int64 { var its []int64 for i := 0; i < len(ids); i++ { var t = ids[i] var it = IdList[t] its = append(its, it) } return its } func save() { data, _ := json.MarshalIndent(dataSource, "", "\t\t") err := cutil.SaveFile(DATA_SOURCE_FILE, data) if err != nil { fmt.Printf("save internal data file error %d\n", err) return } //push() } func AuthInternalId(ctx *gin.Context) { // 文件全路径名 pFile, err := os.Open(DATA_SOURCE_FILE) if err != nil { _ = fmt.Errorf("打开文件失败,filename=%v, err=%v", DATA_SOURCE_FILE, err) return } defer func(pFile *os.File) { err := pFile.Close() if err != nil { _ = fmt.Errorf("关闭文件失败,filename=%v, err=%v", DATA_SOURCE_FILE, err) } }(pFile) md5h := md5.New() io.Copy(md5h, pFile) code := hex.EncodeToString(md5h.Sum(nil)) ctx.JSON(200, code) } func push() { url := "" data, _ := json.MarshalIndent(dataSource, "", "\t\t") st := string(data) cutil.Post(url, st) }