-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathextract.go
More file actions
68 lines (57 loc) · 1.6 KB
/
Copy pathextract.go
File metadata and controls
68 lines (57 loc) · 1.6 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
// Copyright (c) 2025, Roel Schut. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package env
import (
"reflect"
"github.com/go-pogo/env/envtag"
"github.com/go-pogo/errors"
)
// Extract environment variables names and values from the provided struct v.
func Extract(v any) (map[string]any, error) {
return NewExtractor().Extract(v)
}
// An Extractor extracts environment variables names and values from a struct
// value.
type Extractor struct {
TagOptions
}
// NewExtractor returns a new [Extractor].
func NewExtractor() *Extractor {
return &Extractor{
TagOptions: envtag.DefaultOptions(),
}
}
// WithTagOptions sets TagOptions to the provided [TagOptions] opts.
func (ex *Extractor) WithTagOptions(opts TagOptions) *Extractor {
ex.TagOptions = opts
return ex
}
// Extract environment variables names and values from the provided struct v.
func (ex *Extractor) Extract(v any) (map[string]any, error) {
rv, ok := v.(reflect.Value)
if !ok {
rv = reflect.ValueOf(v)
}
if underlyingKind(rv.Type()) != reflect.Struct {
return nil, errors.New(ErrStructExpected)
}
res := make(map[string]any)
trav := &traverser{
TagOptions: ex.TagOptions,
isKnownType: typeKnownByUnmarshaler,
handleField: func(rv reflect.Value, tag envtag.Tag) (err error) {
if rv.IsZero() && tag.Default != "" {
if rv, err = defaultValue(rv.Type(), tag.DefaultValue()); err != nil {
return err
}
}
res[tag.Name] = rv.Interface()
return nil
},
}
if err := trav.start(rv); err != nil {
return res, err
}
return res, nil
}