github.com/sohaha/zlsgo@v1.7.13-0.20240501141223-10dd1a906f76/zcache/tofile/tofile.go (about)

     1  package tofile
     2  
     3  import (
     4  	"encoding/gob"
     5  	"path/filepath"
     6  	"time"
     7  
     8  	"github.com/sohaha/zlsgo/zcache"
     9  	"github.com/sohaha/zlsgo/zfile"
    10  	"github.com/sohaha/zlsgo/zjson"
    11  	"github.com/sohaha/zlsgo/zstring"
    12  )
    13  
    14  type (
    15  	persistenceSt struct {
    16  		Data             interface{}
    17  		LifeSpan         time.Duration
    18  		IntervalLifeSpan bool
    19  	}
    20  )
    21  
    22  func PersistenceToFile(table *zcache.Table, file string, DisableAutoLoad bool, register ...interface{}) (save func() error, err error) {
    23  	gob.Register(&persistenceSt{})
    24  	file = zfile.RealPath(file)
    25  
    26  	for k := range register {
    27  		gob.Register(register[k])
    28  	}
    29  
    30  	if !DisableAutoLoad && zfile.FileExist(file) {
    31  		var content []byte
    32  		content, err = zfile.ReadFile(file)
    33  		if err != nil {
    34  			return
    35  		}
    36  		zjson.ParseBytes(content).ForEach(func(k, v *zjson.Res) (b bool) {
    37  			b = true
    38  			key := k.String()
    39  			base64 := zstring.String2Bytes(v.String())
    40  			base64, err = zstring.Base64Decode(base64)
    41  			if err != nil {
    42  				return false
    43  			}
    44  			var value interface{}
    45  			value, err = zstring.UnSerialize(base64)
    46  			if err != nil {
    47  				return false
    48  			}
    49  
    50  			if persistence, ok := value.(*persistenceSt); ok {
    51  				table.SetRaw(key, persistence.Data, persistence.LifeSpan, persistence.IntervalLifeSpan)
    52  			}
    53  			return
    54  		})
    55  	}
    56  	save = func() error {
    57  		jsonData := exportJSON(table)
    58  		_ = zfile.RealPathMkdir(filepath.Dir(file))
    59  
    60  		return zfile.WriteFile(file, zstring.String2Bytes(jsonData))
    61  	}
    62  	return
    63  }
    64  
    65  func exportJSON(table *zcache.Table, registers ...interface{}) string {
    66  	for i := range registers {
    67  		gob.Register(registers[i])
    68  	}
    69  	jsonData := "{}"
    70  	table.ForEachRaw(func(key string, item *zcache.Item) bool {
    71  		item.RLock()
    72  		v := &persistenceSt{
    73  			Data:             item.Data(),
    74  			LifeSpan:         item.LifeSpan(),
    75  			IntervalLifeSpan: item.IntervalLifeSpan(),
    76  		}
    77  		item.RUnlock()
    78  		value, err := zstring.Serialize(v)
    79  		if err != nil {
    80  			return true
    81  		}
    82  		jsonData, _ = zjson.Set(jsonData, key, zstring.Base64Encode(value))
    83  
    84  		return true
    85  	})
    86  	return jsonData
    87  }