Created
February 15, 2022 13:02
-
-
Save fracasula/795ea50489f9d03ef41c2e5973b344c1 to your computer and use it in GitHub Desktop.
Golang MongoDB UUID
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package mongouuid | |
import ( | |
"fmt" | |
"github.com/google/uuid" | |
"go.mongodb.org/mongo-driver/bson/bsontype" | |
"go.mongodb.org/mongo-driver/x/bsonx/bsoncore" | |
) | |
type UUID struct { | |
data uuid.UUID | |
} | |
func (u *UUID) String() string { | |
return u.data.String() | |
} | |
func (u UUID) MarshalBSONValue() (bsontype.Type, []byte, error) { | |
return bsontype.Binary, bsoncore.AppendBinary(nil, bsontype.BinaryUUID, u.data[:]), nil | |
} | |
func (u *UUID) UnmarshalBSONValue(t bsontype.Type, raw []byte) error { | |
if t != bsontype.Binary { | |
return fmt.Errorf("expected Binary type, got %+v", t) | |
} | |
subtype, data, _, ok := bsoncore.ReadBinary(raw) | |
if !ok { | |
return fmt.Errorf("not enough bytes to unmarshal bson value") | |
} | |
if subtype != bsontype.BinaryUUID { | |
return fmt.Errorf("expected UUID subtype, got %+v", t) | |
} | |
var err error | |
u.data, err = uuid.FromBytes(data) | |
return err | |
} | |
func FromString(str string) (v UUID, err error) { | |
v.data, err = uuid.Parse(str) | |
return | |
} | |
func FromBytes(b []byte) (v UUID, err error) { | |
v.data, err = uuid.FromBytes(b) | |
return | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks to the right subtype (i.e.
0x04
, seebsontype.BinaryUUID
), now it shows correctly from the command line as well: