-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathinit.go
46 lines (35 loc) · 1017 Bytes
/
init.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
package zconfig
import (
"context"
"fmt"
"reflect"
)
type Initializable interface {
Init(context.Context) error
}
type initializableDeprecated interface {
Init() error
}
// Used for type comparison.
var typeInitializable = reflect.TypeOf((*Initializable)(nil)).Elem()
var typeInitializableDeprecated = reflect.TypeOf((*initializableDeprecated)(nil)).Elem()
func Initialize(ctx context.Context, field *Field) error {
// Not initializable, nothing to do.
if field.Value.Type().Implements(typeInitializable) {
// Initialize the element itself via the interface.
err := field.Value.Interface().(Initializable).Init(ctx)
if err != nil {
return fmt.Errorf("initializing field: %w", err)
}
return nil
}
if field.Value.Type().Implements(typeInitializableDeprecated) {
// Initialize the element itself via the interface.
err := field.Value.Interface().(initializableDeprecated).Init()
if err != nil {
return fmt.Errorf("initializing field: %w", err)
}
return nil
}
return nil
}