2023-09-29 08:21:32 +00:00
|
|
|
package hook
|
|
|
|
|
|
|
|
import (
|
|
|
|
"reflect"
|
|
|
|
|
|
|
|
"github.com/mitchellh/mapstructure"
|
2023-10-25 15:10:45 +00:00
|
|
|
"golang.org/x/exp/constraints"
|
2023-09-29 08:21:32 +00:00
|
|
|
)
|
|
|
|
|
2023-10-25 15:10:45 +00:00
|
|
|
func EnumHookFunc[T constraints.Integer](resolve func(string) (T, error)) mapstructure.DecodeHookFuncType {
|
2023-09-29 08:21:32 +00:00
|
|
|
return func(
|
|
|
|
f reflect.Type,
|
|
|
|
t reflect.Type,
|
|
|
|
data interface{},
|
|
|
|
) (interface{}, error) {
|
|
|
|
if f.Kind() != reflect.String {
|
|
|
|
return data, nil
|
|
|
|
}
|
2023-10-25 15:10:45 +00:00
|
|
|
if t != reflect.TypeOf(T(0)) {
|
2023-09-29 08:21:32 +00:00
|
|
|
return data, nil
|
|
|
|
}
|
2023-10-25 15:10:45 +00:00
|
|
|
return resolve(data.(string))
|
2023-09-29 08:21:32 +00:00
|
|
|
}
|
|
|
|
}
|