Add JSON support to ext/gofrs-uuid
This commit is contained in:
@@ -10,6 +10,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
var errUndefined = errors.New("cannot encode status undefined")
|
var errUndefined = errors.New("cannot encode status undefined")
|
||||||
|
var errBadStatus = errors.New("invalid status")
|
||||||
|
|
||||||
type UUID struct {
|
type UUID struct {
|
||||||
UUID uuid.UUID
|
UUID uuid.UUID
|
||||||
@@ -172,3 +173,32 @@ func (dst *UUID) Scan(src interface{}) error {
|
|||||||
func (src UUID) Value() (driver.Value, error) {
|
func (src UUID) Value() (driver.Value, error) {
|
||||||
return pgtype.EncodeValueText(src)
|
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
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user