2
0

Add JSON support to ext/gofrs-uuid

This commit is contained in:
Jack Christensen
2020-04-02 14:01:16 -05:00
parent ef5f8b54af
commit 9016875cae
+30
View File
@@ -10,6 +10,7 @@ import (
)
var errUndefined = errors.New("cannot encode status undefined")
var errBadStatus = errors.New("invalid status")
type UUID struct {
UUID uuid.UUID
@@ -172,3 +173,32 @@ func (dst *UUID) Scan(src interface{}) error {
func (src UUID) Value() (driver.Value, error) {
return pgtype.EncodeValueText(src)
}
func (src UUID) MarshalJSON() ([]byte, error) {
switch src.Status {
case pgtype.Present:
return []byte(`"` + src.UUID.String() + `"`), nil
case pgtype.Null:
return []byte("null"), nil
case pgtype.Undefined:
return nil, errUndefined
}
return nil, errBadStatus
}
func (dst *UUID) UnmarshalJSON(b []byte) error {
u := uuid.NullUUID{}
err := u.UnmarshalJSON(b)
if err != nil {
return err
}
status := pgtype.Null
if u.Valid {
status = pgtype.Present
}
*dst = UUID{UUID: u.UUID, Status: status}
return nil
}