game/common/serialization/serialization.go

49 lines
1.1 KiB
Go
Raw Normal View History

2025-05-31 23:34:58 +08:00
package serialization
import (
2025-06-04 13:08:58 +08:00
"github.com/fox/fox/log"
2025-06-04 23:11:32 +08:00
"github.com/fox/fox/mapstruct"
"reflect"
2025-06-04 13:08:58 +08:00
"time"
)
2025-05-31 23:34:58 +08:00
2025-06-04 23:11:32 +08:00
const (
timeFormat = "2006-01-02 15:04:05"
)
func time2stringHook(v reflect.Value, _ reflect.StructField) (any, error) {
if v.Type() == reflect.TypeOf(time.Time{}) {
if t, ok := v.Interface().(time.Time); ok {
return t.Format(timeFormat), nil
}
2025-05-31 23:34:58 +08:00
}
2025-06-04 23:11:32 +08:00
return v, nil
2025-05-31 23:34:58 +08:00
}
2025-06-04 13:08:58 +08:00
type resultT[T any] struct {
ret T
}
2025-06-04 23:11:32 +08:00
func string2timeHook(s string, _ reflect.StructField) (any, error) {
return time.Parse(timeFormat, s)
}
2025-06-04 23:11:32 +08:00
func StructToMap(_struct interface{}) map[string]interface{} {
result, err := mapstruct.ToMap(_struct,
mapstruct.WithTypeHook(reflect.TypeOf(time.Time{}), time2stringHook),
)
2025-06-04 13:08:58 +08:00
if err != nil {
2025-06-04 23:11:32 +08:00
log.ErrorF("struct:%v to map error:%v", _struct, err)
return make(map[string]interface{})
}
2025-06-04 23:11:32 +08:00
return result
}
2025-06-04 23:11:32 +08:00
func MapToStruct[T any](maps map[string]string) (*T, error) {
result := &resultT[T]{}
err := mapstruct.ToStruct(maps, &result.ret,
mapstruct.WithStringTypeHook(reflect.TypeOf(time.Time{}), string2timeHook),
)
return &result.ret, err
}