Skip to content

Commit c198c4f

Browse files
committed
Add viper bind env func
1 parent dca31fe commit c198c4f

File tree

7 files changed

+173
-36
lines changed

7 files changed

+173
-36
lines changed

go.mod

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,10 @@
11
module github.com/dsxack/go/v2
22

33
go 1.13
4+
5+
require (
6+
github.com/go-kit/kit v0.10.0
7+
github.com/sirupsen/logrus v1.6.0
8+
github.com/spf13/viper v1.7.1
9+
github.com/stretchr/testify v1.6.1
10+
)

kit/go.sum renamed to go.sum

Lines changed: 130 additions & 0 deletions
Large diffs are not rendered by default.

kit/go.mod

Lines changed: 0 additions & 8 deletions
This file was deleted.

logrus/formatter/omitdoublesformatter_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ package formatter_test
22

33
import (
44
"bytes"
5-
_logrus "github.com/dsxack/go/logrus/formatter"
5+
_logrus "github.com/dsxack/go/v2/logrus/formatter"
66
"github.com/sirupsen/logrus"
77
"github.com/stretchr/testify/assert"
88
"testing"

logrus/go.mod

Lines changed: 0 additions & 8 deletions
This file was deleted.

logrus/go.sum

Lines changed: 0 additions & 19 deletions
This file was deleted.

viper/bindenv.go

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package viper
2+
3+
import (
4+
"github.com/spf13/viper"
5+
"reflect"
6+
"strings"
7+
)
8+
9+
func BindEnvs(v *viper.Viper, iface interface{}, parts ...string) error {
10+
ifv := reflect.ValueOf(iface)
11+
ift := reflect.TypeOf(iface)
12+
for i := 0; i < ift.NumField(); i++ {
13+
fieldv := ifv.Field(i)
14+
t := ift.Field(i)
15+
name := strings.ToLower(t.Name)
16+
tag, ok := t.Tag.Lookup("mapstructure")
17+
if ok {
18+
name = tag
19+
}
20+
path := append(parts, name)
21+
switch fieldv.Kind() {
22+
case reflect.Struct:
23+
err := BindEnvs(v, fieldv.Interface(), path...)
24+
if err != nil {
25+
return err
26+
}
27+
default:
28+
err := v.BindEnv(strings.Join(path, "."))
29+
if err != nil {
30+
return err
31+
}
32+
}
33+
}
34+
return nil
35+
}

0 commit comments

Comments
 (0)