github.com/TeaOSLab/EdgeNode@v1.3.8/internal/caches/list_file_kv_objects.go (about) 1 // Copyright 2024 GoEdge CDN goedge.cdn@gmail.com. All rights reserved. Official site: https://goedge.cn . 2 3 package caches 4 5 import ( 6 "encoding/binary" 7 "encoding/json" 8 "strings" 9 ) 10 11 // ItemKVEncoder item encoder 12 type ItemKVEncoder[T interface{ *Item }] struct { 13 } 14 15 func NewItemKVEncoder[T interface{ *Item }]() *ItemKVEncoder[T] { 16 return &ItemKVEncoder[T]{} 17 } 18 19 func (this *ItemKVEncoder[T]) Encode(value T) ([]byte, error) { 20 return json.Marshal(value) 21 } 22 23 func (this *ItemKVEncoder[T]) EncodeField(value T, fieldName string) ([]byte, error) { 24 switch fieldName { 25 case "createdAt": 26 var b = make([]byte, 4) 27 var createdAt = any(value).(*Item).CreatedAt 28 binary.BigEndian.PutUint32(b, uint32(createdAt)) 29 return b, nil 30 case "staleAt": 31 var b = make([]byte, 4) 32 var staleAt = any(value).(*Item).StaleAt 33 if staleAt < 0 { 34 staleAt = 0 35 } 36 binary.BigEndian.PutUint32(b, uint32(staleAt)) 37 return b, nil 38 case "serverId": 39 var b = make([]byte, 4) 40 var serverId = any(value).(*Item).ServerId 41 if serverId < 0 { 42 serverId = 0 43 } 44 binary.BigEndian.PutUint32(b, uint32(serverId)) 45 return b, nil 46 case "key": 47 return []byte(any(value).(*Item).Key), nil 48 case "wildKey": 49 var key = any(value).(*Item).Key 50 var dotIndex = strings.Index(key, ".") 51 if dotIndex > 0 { 52 var slashIndex = strings.LastIndex(key[:dotIndex], "/") 53 if slashIndex > 0 { 54 key = key[:dotIndex][:slashIndex+1] + "*" + key[dotIndex:] 55 } 56 } 57 58 return []byte(key), nil 59 } 60 return nil, nil 61 } 62 63 func (this *ItemKVEncoder[T]) Decode(valueBytes []byte) (value T, err error) { 64 err = json.Unmarshal(valueBytes, &value) 65 return 66 }