-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathm.go
More file actions
82 lines (71 loc) · 2.03 KB
/
m.go
File metadata and controls
82 lines (71 loc) · 2.03 KB
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
77
78
79
80
81
82
package envg
import (
"fmt"
"os"
"reflect"
"strconv"
)
func LoadConfig(cfg any) error {
v := reflect.ValueOf(cfg)
if v.Kind() != reflect.Ptr || v.Elem().Kind() != reflect.Struct {
return fmt.Errorf("LoadConfig only accepts a pointer to a struct")
}
// Get the reflect.Value of the struct (dereference the pointer)
v = v.Elem()
for i := 0; i < v.NumField(); i++ {
field := v.Field(i)
fieldType := v.Type().Field(i)
if fieldType.IsExported() {
envValue, err := getEnv("env" + fieldType.Name)
if err != nil {
return err
}
if err = setFieldFromString(field, envValue); err != nil {
return fmt.Errorf("error setting field %s: %v", fieldType.Name, err)
}
}
}
return nil
}
func setFieldFromString(field reflect.Value, value string) error {
switch field.Kind() {
case reflect.String:
field.SetString(value)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
intValue, err := parseInteger(value, field.Type().Bits())
if err != nil {
return err
}
field.SetInt(intValue)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
uintValue, err := parseUnsignedInteger(value, field.Type().Bits())
if err != nil {
return err
}
field.SetUint(uintValue)
case reflect.Bool:
boolValue, err := strconv.ParseBool(value)
if err != nil {
return err
}
field.SetBool(boolValue)
default:
return fmt.Errorf("unsupported field type: %v", field.Type())
}
return nil
}
// parseInteger parses a string into a signed integer based on the provided bit size.
func parseInteger(value string, bitSize int) (int64, error) {
return strconv.ParseInt(value, 10, bitSize)
}
// parseUnsignedInteger parses a string into an unsigned integer based on the provided bit size.
func parseUnsignedInteger(value string, bitSize int) (uint64, error) {
return strconv.ParseUint(value, 10, bitSize)
}
func getEnv(key string) (string, error) {
val, exists := os.LookupEnv(key)
if !exists {
return "", fmt.Errorf("environment variable %s is not set", key)
}
return val, nil
}