-
Notifications
You must be signed in to change notification settings - Fork 53
/
generic.go
71 lines (61 loc) · 1.5 KB
/
generic.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package util
import (
"encoding/json"
"reflect"
"strings"
"github.com/iancoleman/strcase"
"github.com/mitchellh/mapstructure"
"github.com/rancher/opni/pkg/logger"
"go.uber.org/zap"
"google.golang.org/protobuf/proto"
)
var (
stackLg = logger.New(logger.WithZapOptions(zap.AddStacktrace(zap.InfoLevel)))
errType = reflect.TypeOf((*error)(nil)).Elem()
)
func Must[T any](t T, err ...error) T {
if len(err) > 0 {
if err[0] != nil {
stackLg.Panic(err)
}
}
if typ := reflect.TypeOf(t); typ != nil && typ.Implements(errType) {
stackLg.Panic(err)
}
return t
}
func DecodeStruct[T any](input interface{}) (*T, error) {
output := new(T)
config := &mapstructure.DecoderConfig{
Metadata: nil,
Result: output,
TagName: "json",
Squash: true,
MatchName: func(mapKey, fieldName string) bool {
return strings.EqualFold(mapKey, fieldName) ||
strings.EqualFold(strcase.ToSnake(mapKey), fieldName) ||
strings.EqualFold(strcase.ToLowerCamel(mapKey), fieldName)
},
}
// NewDecoder cannot fail - the only error condition is if
// config.Result is not a pointer
decoder := Must(mapstructure.NewDecoder(config))
if err := decoder.Decode(input); err != nil {
return nil, err
}
return output, nil
}
func DeepCopyInto[T any](out, in *T) {
Must(json.Unmarshal(Must(json.Marshal(in)), out))
}
func DeepCopy[T any](in *T) *T {
out := new(T)
DeepCopyInto(out, in)
return out
}
func Pointer[T any](t T) *T {
return &t
}
func ProtoClone[T proto.Message](msg T) T {
return proto.Clone(msg).(T)
}