isStructPtr and unmarshal functions
This commit is contained in:
commit
601ec4e86d
|
@ -0,0 +1,29 @@
|
|||
package confection2
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
)
|
||||
|
||||
var (
|
||||
// config stores application config.
|
||||
config interface{}
|
||||
)
|
||||
|
||||
func isStructPtr(target interface{}) bool {
|
||||
if val := reflect.ValueOf(target); val.Kind() == reflect.Ptr {
|
||||
if val = reflect.Indirect(val); val.Kind() == reflect.Struct {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func unmarshal(body []byte, target interface{}) error {
|
||||
if err := json.Unmarshal(body, target); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
|
@ -0,0 +1,44 @@
|
|||
package confection2
|
||||
|
||||
import "testing"
|
||||
|
||||
type testConf struct {
|
||||
Foo string `json:"foo"`
|
||||
Bar int `json:"bar"`
|
||||
}
|
||||
|
||||
const (
|
||||
goodJSON = `{"foo": "baz", "bar": 1}`
|
||||
badJSON = `{"foo": "noooo...`
|
||||
)
|
||||
|
||||
func TestIsStructPtr(t *testing.T) {
|
||||
if ok := isStructPtr(1); ok {
|
||||
t.Error("Integer recognized as a struct pointer")
|
||||
}
|
||||
if ok := isStructPtr(testConf{}); ok {
|
||||
t.Error("Struct instance recognized as a struct pointer")
|
||||
}
|
||||
if ok := isStructPtr(&testConf{}); !ok {
|
||||
t.Error("Struct pointer was not recognized")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnmarshal(t *testing.T) {
|
||||
conf := testConf{}
|
||||
var i interface{} = &conf
|
||||
|
||||
if err := unmarshal([]byte(badJSON), i); err == nil {
|
||||
t.Error("Expected error")
|
||||
}
|
||||
|
||||
if err := unmarshal([]byte(goodJSON), i); err != nil {
|
||||
t.Error("Unexpected error")
|
||||
}
|
||||
if conf.Foo != "baz" {
|
||||
t.Errorf("Expected Foo to equal %q, got %q", "baz", conf.Foo)
|
||||
}
|
||||
if conf.Bar != 1 {
|
||||
t.Errorf("Expected Bar to equal %q, got %q", 1, conf.Bar)
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue