1 Star 1 Fork 0

Cinus/go-tagexpr

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
func.go 1.96 KB
一键复制 编辑 原始数据 按行查看 历史
andeyalee 提交于 2019-09-04 18:20 . chore(binding): Update Type Unmarshalor
package binding
import (
"errors"
"fmt"
"reflect"
"time"
)
var (
jsonUnmarshalFunc func(data []byte, v interface{}) error
jsonIndependentRequired = true
)
// ResetJSONUnmarshaler reset the JSON Unmarshal function.
// NOTE: verifyingRequired is true if the required tag is supported.
func ResetJSONUnmarshaler(verifyingRequired bool, fn func(data []byte, v interface{}) error) {
jsonIndependentRequired = !verifyingRequired
jsonUnmarshalFunc = fn
}
var typeUnmarshalFuncs = make(map[reflect.Type]func(string, bool) (reflect.Value, error))
// MustRegTypeUnmarshal registers unmarshalor function of type.
// NOTE:
// panic if exist error.
func MustRegTypeUnmarshal(t reflect.Type, fn func(v string, emptyAsZero bool) (reflect.Value, error)) {
err := RegTypeUnmarshal(t, fn)
if err != nil {
panic(err)
}
}
// RegTypeUnmarshal registers unmarshalor function of type.
func RegTypeUnmarshal(t reflect.Type, fn func(v string, emptyAsZero bool) (reflect.Value, error)) error {
// check
switch t.Kind() {
case reflect.String, reflect.Bool,
reflect.Float32, reflect.Float64,
reflect.Int, reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8,
reflect.Uint, reflect.Uint64, reflect.Uint32, reflect.Uint16, reflect.Uint8:
return errors.New("registration type cannot be a basic type")
case reflect.Ptr:
return errors.New("registration type cannot be a pointer type")
}
// test
vv, err := fn("", true)
if err != nil {
return fmt.Errorf("test fail: %s", err)
}
if tt := vv.Type(); tt != t {
return fmt.Errorf("test fail: expect return value type is %s, but got %s", t.String(), tt.String())
}
typeUnmarshalFuncs[t] = fn
return nil
}
func init() {
MustRegTypeUnmarshal(reflect.TypeOf(time.Time{}), func(v string, emptyAsZero bool) (reflect.Value, error) {
if v == "" && emptyAsZero {
return reflect.ValueOf(time.Time{}), nil
}
t, err := time.Parse(time.RFC3339, v)
if err != nil {
return reflect.Value{}, err
}
return reflect.ValueOf(t), nil
})
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/cinus/go-tagexpr.git
git@gitee.com:cinus/go-tagexpr.git
cinus
go-tagexpr
go-tagexpr
v2.4.0

搜索帮助