-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathdecoding.go
43 lines (40 loc) · 1.14 KB
/
decoding.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
package config
import (
"fmt"
"math/big"
"reflect"
"github.com/mitchellh/mapstructure"
)
// bigIntHookFunc is a mapstructure HookFunc to handle both ints and strings for big.Int
// viper doesn't handle big ints nicely out of the box (in yaml they might be provided as numbers or strings in various formats
func bigIntHookFunc() mapstructure.DecodeHookFuncType {
return func(
f reflect.Type,
t reflect.Type,
data interface{},
) (interface{}, error) {
// Check if we are trying to map into a *big.Int
if t == reflect.TypeOf(&big.Int{}) {
switch data := data.(type) {
case int:
// Convert int to *big.Int
return big.NewInt(int64(data)), nil
case int64:
// Convert int64 to *big.Int
return big.NewInt(data), nil
case float64:
// Convert float64 to *big.Int (if the YAML parser gives float types)
return big.NewInt(int64(data)), nil
case string:
// Convert string to *big.Int
bi := new(big.Int)
_, ok := bi.SetString(data, 10) // Assuming base 10 for string conversion
if !ok {
return nil, fmt.Errorf("cannot convert %s to big.Int", data)
}
return bi, nil
}
}
return data, nil
}
}