Skip to content

Commit 73c2dbe

Browse files
author
paulatwilson
committed
Basic changes
1 parent 80d86bf commit 73c2dbe

File tree

3 files changed

+41
-0
lines changed

3 files changed

+41
-0
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,3 +22,4 @@ _testmain.go
2222
*.exe
2323
*.test
2424
*.prof
25+
.idea

gonfig.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ package gonfig
66
import (
77
"fmt"
88
"reflect"
9+
"go/types"
910
)
1011

1112
type Gonfig interface {
@@ -15,6 +16,7 @@ type Gonfig interface {
1516
GetFloat(key string, defaultValue interface{}) (float64, error)
1617
GetBool(key string, defaultValue interface{}) (bool, error)
1718
GetAs(key string, target interface{}) error
19+
GetArray(key string, target []struct{}) ([]struct{}, error)
1820
}
1921

2022
type KeyNotFoundError struct {

json.go

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ import (
66
"io/ioutil"
77
"path"
88
"strings"
9+
"os"
10+
"reflect"
911
)
1012

1113
// Gonfig implementation
@@ -14,6 +16,22 @@ type JsonGonfig struct {
1416
obj map[string]interface{}
1517
}
1618

19+
// FromJsonFile opens the file supplied and calls
20+
// FromJson function
21+
func FromJsonFile(filename string) (Gonfig, error) {
22+
f, err := os.Open(filename)
23+
if err != nil {
24+
return nil, err
25+
}
26+
defer f.Close()
27+
config, err := FromJson(f)
28+
if err != nil {
29+
return nil, err
30+
}
31+
32+
return config, nil
33+
}
34+
1735
// FromJson reads the contents from the supplied reader.
1836
// The content is parsed as json into a map[string]interface{}.
1937
// It returns a JsonGonfig struct pointer and any error encountered
@@ -44,6 +62,26 @@ func (jgonfig *JsonGonfig) GetString(key string, defaultValue interface{}) (stri
4462
}
4563
}
4664

65+
66+
func (jgonfig *JsonGonfig) GetArray(key string, target []struct{}) ([]struct{}, error) {
67+
68+
69+
configValue, err := jgonfig.Get(key, "")
70+
if err != nil {
71+
return []struct{}{}, err
72+
}
73+
if stringValue, ok := configValue.(string); ok {
74+
75+
keysBody := []byte(stringValue)
76+
json.Unmarshal(keysBody, &target)
77+
78+
return target, nil
79+
} else {
80+
return []struct{}{}, &UnexpectedValueTypeError{key: key, value: configValue, message: "value is not a string"}
81+
}
82+
}
83+
84+
4785
// GetInt uses Get to fetch the value behind the supplied key.
4886
// It returns a int with either the retreived value or the default value and any error encountered.
4987
// If value is not a int it returns a UnexpectedValueTypeError

0 commit comments

Comments
 (0)