-
Notifications
You must be signed in to change notification settings - Fork 0
/
config_hook.go
76 lines (56 loc) · 1.34 KB
/
config_hook.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
72
73
74
75
76
package main
import (
"fmt"
"net/url"
"reflect"
"strings"
"github.com/mitchellh/mapstructure"
"github.com/spf13/pflag"
)
func mStringToURLHookFunc() mapstructure.DecodeHookFuncType {
return func(f reflect.Type, t reflect.Type, data any) (value any, err error) {
var ptr bool
if f.Kind() != reflect.String {
return data, nil
}
prefixType := ""
if t.Kind() == reflect.Ptr {
ptr = true
prefixType = "*"
}
expectedType := reflect.TypeOf(url.URL{})
if ptr && t.Elem() != expectedType {
return data, nil
} else if !ptr && t != expectedType {
return data, nil
}
dataStr := data.(string)
var result *url.URL
if dataStr != "" {
if result, err = url.Parse(dataStr); err != nil {
return nil, fmt.Errorf("could not decode '%s' to a %s%s: %w", dataStr, prefixType, expectedType, err)
}
}
if ptr {
return result, nil
}
if result == nil {
return url.URL{}, nil
}
return *result, nil
}
}
func configCallbackPosFlag(prefix string) func(flag *pflag.Flag) (key string, value any) {
return func(flag *pflag.Flag) (key string, value any) {
if !flag.Changed {
return "", nil
}
var parts []string
if prefix != "" {
parts = append(parts, prefix)
}
parts = append(parts, strings.ReplaceAll(flag.Name, "-", "_"))
key = strings.Join(parts, ".")
return key, flag.Value.String()
}
}