-
Notifications
You must be signed in to change notification settings - Fork 1
/
transformer.go
65 lines (51 loc) · 1.4 KB
/
transformer.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
package config
import (
"context"
"github.com/alexfalkowski/go-service/config"
"github.com/alexfalkowski/go-service/meta"
"github.com/alexfalkowski/konfig/server/config/errors"
"github.com/alexfalkowski/konfig/server/config/provider"
)
// Transformer for config.
type Transformer struct {
pt *provider.Transformer
}
// NewTransformer for config.
func NewTransformer(pt *provider.Transformer) *Transformer {
return &Transformer{pt: pt}
}
// Transform config.
func (t *Transformer) Transform(ctx context.Context, bytes []byte) ([]byte, error) {
cfg := config.Map{}
if err := config.UnmarshalFromBytes(bytes, cfg); err != nil {
meta.WithAttribute(ctx, "config.unmarshal_error", err.Error())
return nil, errors.ErrUnmarshalError
}
if err := t.traverse(ctx, cfg); err != nil {
meta.WithAttribute(ctx, "config.traverse_error", err.Error())
return nil, errors.ErrTraverseError
}
data, err := config.MarshalToBytes(cfg)
if err != nil {
meta.WithAttribute(ctx, "config.marshal_error", err.Error())
return nil, errors.ErrMarshalError
}
return data, nil
}
func (t *Transformer) traverse(ctx context.Context, cfg config.Map) error {
for key, val := range cfg {
switch v := val.(type) {
case string:
vt, err := t.pt.Transform(ctx, v)
if err != nil {
return err
}
cfg[key] = vt
case config.Map:
if err := t.traverse(ctx, v); err != nil {
return err
}
}
}
return nil
}