wrapper/object.go

148 lines
2.8 KiB
Go

// Package wrapper ...
//
// Description : wrapper ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2023-06-01 18:33
package wrapper
import (
"encoding/json"
"errors"
"git.zhangdeman.cn/zhangdeman/serialize"
"reflect"
)
// ObjectData 对象类型, 支持 nil / Map / Struct
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 18:36 2023/6/1
func ObjectData(data interface{}) *ObjectType {
ot := &ObjectType{
source: data,
data: map[interface{}]interface{}{},
byteData: []byte{},
isValid: true,
invalidErr: errors.New("data is invalid"),
}
if nil == ot {
return ot
}
reflectType := reflect.TypeOf(data)
switch reflectType.Kind() {
case reflect.Map:
fallthrough
case reflect.Struct:
ot.byteData, _ = json.Marshal(ot.source)
default:
// 数据类型不是 nil / map / struct 之一
ot.isValid = false
}
return ot
}
// ObjectType ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 18:38 2023/6/1
type ObjectType struct {
source interface{}
data map[interface{}]interface{}
byteData []byte
isValid bool
invalidErr error
}
// IsValid 是否有效对象数据
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 18:49 2023/6/1
func (ot *ObjectType) IsValid() bool {
return ot.isValid
}
// IsNil 是否为nil
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 18:50 2023/6/1
func (ot *ObjectType) IsNil() bool {
return ot.source == nil
}
// ToString 转字符串
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 18:51 2023/6/1
func (ot *ObjectType) ToString() StringResult {
if ot.IsNil() {
return StringResult{
Value: "nil",
Err: nil,
}
}
if !ot.IsValid() {
// 非法对象数据
return StringResult{
Value: "",
Err: errors.New("data is invalid"),
}
}
return StringResult{
Value: string(ot.byteData),
Err: nil,
}
}
// ToMapStringAny ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 16:17 2023/6/2
func (ot *ObjectType) ToMapStringAny() ObjectResult {
res := ObjectResult{
Value: map[string]interface{}{},
Err: nil,
}
if ot.IsNil() {
return res
}
res.Err = serialize.JSON.UnmarshalWithNumber(ot.byteData, &res.Value)
return res
}
// ToStruct ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 16:41 2023/6/2
func (ot *ObjectType) ToStruct(receiver interface{}) error {
if nil == receiver {
return errors.New("receiver is nil")
}
if ot.IsNil() {
return errors.New("data is nil")
}
return serialize.JSON.UnmarshalWithNumber(ot.byteData, receiver)
}
// ToStructIgnoreErr ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 16:42 2023/6/2
func (ot *ObjectType) ToStructIgnoreErr(receiver interface{}) {
if nil == receiver {
return
}
if ot.IsNil() {
return
}
_ = serialize.JSON.UnmarshalWithNumber(ot.byteData, receiver)
}