Skip to content

Commit

Permalink
Let UUID implements Marshaling interface for encoding/json
Browse files Browse the repository at this point in the history
  • Loading branch information
Kasper Middelboe Petersen committed Feb 27, 2014
1 parent 03f7e4f commit d81fa72
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
5 changes: 5 additions & 0 deletions uuid.go
Original file line number Diff line number Diff line change
Expand Up @@ -208,3 +208,8 @@ func (u UUID) Time() time.Time {
nsec := t % 1e7
return time.Unix(sec+timeBase, nsec).UTC()
}

// Marshaling for JSON
func (u UUID) MarshalJSON() ([]byte, error) {
return []byte(`"` + u.String() + `"`), nil
}
9 changes: 9 additions & 0 deletions uuid_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,15 @@ func TestPredefinedUUID(t *testing.T) {
t.Errorf("Version #%d: expected %d got %d", i, testsUUID[i].version, version)
}
}

json, err := uuid.MarshalJSON()
if err != nil {
t.Errorf("MarshalJSON #%d: %v", i, err)
}
expectedJson := `"` + testsUUID[i].input + `"`
if string(json) != expectedJson {
t.Errorf("MarshalJSON #%d: expected %d got %d", i, expectedJson, string(json))
}
}
}

Expand Down

0 comments on commit d81fa72

Please sign in to comment.