commit 601ec4e86dd9058f9286835319902715d74c3fa8 Author: Gregory Eremin Date: Sat Aug 29 12:45:00 2015 +0300 isStructPtr and unmarshal functions diff --git a/confection.go b/confection.go new file mode 100644 index 0000000..88eb651 --- /dev/null +++ b/confection.go @@ -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 +} diff --git a/confection_test.go b/confection_test.go new file mode 100644 index 0000000..01d5055 --- /dev/null +++ b/confection_test.go @@ -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) + } +}