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