add ugorji unmarshaller and address comments

This commit is contained in:
Chao Xu 2015-11-05 13:46:44 -08:00
parent 9d52b0fc08
commit 6419924a5e
2 changed files with 29 additions and 10 deletions

View File

@ -30,7 +30,7 @@ type GroupAndVersion struct {
func (gv *GroupAndVersion) String() string {
// special case of "v1" for backward compatibility
if gv.Group == "" {
if gv.Group == "" && gv.Version == "v1" {
return gv.Version
} else {
return gv.Group + "/" + gv.Version
@ -41,11 +41,12 @@ func ParseGroupVersion(gv string) (GroupAndVersion, error) {
s := strings.Split(gv, "/")
// "v1" is the only special case. Otherwise GroupVersion is expected to contain
// one "/" dividing the string into two parts.
if len(s) == 1 && gv == "v1" {
switch {
case len(s) == 1 && gv == "v1":
return GroupAndVersion{"", "v1"}, nil
} else if len(s) == 2 {
case len(s) == 2:
return GroupAndVersion{s[0], s[1]}, nil
} else {
default:
return GroupAndVersion{}, fmt.Errorf("Unexpected GroupVersion string: %v", gv)
}
}
@ -59,8 +60,7 @@ func (gv GroupAndVersion) MarshalJSON() ([]byte, error) {
return json.Marshal(s)
}
// UnmarshalJSON implements the json.Unmarshaller interface.
func (gv *GroupAndVersion) UnmarshalJSON(value []byte) error {
func (gv *GroupAndVersion) unmarshal(value []byte) error {
var s string
if err := json.Unmarshal(value, &s); err != nil {
return err
@ -69,7 +69,16 @@ func (gv *GroupAndVersion) UnmarshalJSON(value []byte) error {
if err != nil {
return err
}
gv.Group = parsed.Group
gv.Version = parsed.Version
*gv = parsed
return nil
}
// UnmarshalJSON implements the json.Unmarshaller interface.
func (gv *GroupAndVersion) UnmarshalJSON(value []byte) error {
return gv.unmarshal(value)
}
// UnmarshalTEXT implements the Ugorji's encoding.TextUnmarshaler interface.
func (gv *GroupAndVersion) UnmarshalText(value []byte) error {
return gv.unmarshal(value)
}

View File

@ -20,6 +20,8 @@ import (
"encoding/json"
"reflect"
"testing"
"github.com/ugorji/go/codec"
)
type GroupVersionHolder struct {
@ -37,11 +39,19 @@ func TestGroupVersionUnmarshalJSON(t *testing.T) {
for _, c := range cases {
var result GroupVersionHolder
// test golang lib's JSON codec
if err := json.Unmarshal([]byte(c.input), &result); err != nil {
t.Errorf("Failed to unmarshal input '%v': %v", c.input, err)
t.Errorf("JSON codec failed to unmarshal input '%v': %v", c.input, err)
}
if !reflect.DeepEqual(result.GV, c.expect) {
t.Errorf("Failed to unmarshal input '%s': expected %+v, got %+v", c.input, c.expect, result.GV)
t.Errorf("JSON codec failed to unmarshal input '%s': expected %+v, got %+v", c.input, c.expect, result.GV)
}
// test the Ugorji codec
if err := codec.NewDecoderBytes(c.input, new(codec.JsonHandle)).Decode(&result); err != nil {
t.Errorf("Ugorji codec failed to unmarshal input '%v': %v", c.input, err)
}
if !reflect.DeepEqual(result.GV, c.expect) {
t.Errorf("Ugorji codec failed to unmarshal input '%s': expected %+v, got %+v", c.input, c.expect, result.GV)
}
}
}