2

I would like to have some kind of a "hook" that runs whenever I get a specific type of object from the database. I thought the Unmarshaler interface is perfect for that, but... How can I implement that interface without manually unmarshalling every single field myself?

I thought of doing something like this:

func (t *T) UnmarshalBSON(b []byte) error {
    // Simply unmarshal `b` into `t` like it would otherwise
    bson.Unmarshal(b, t) // Obviously this won't work, it'll be an infinite loop
    // Do something here
    return nil
}

How could I achieve this without manually unmarshalling the fields using the reflect pkg?

Andrew
  • 2,063
  • 3
  • 24
  • 40
  • 1
    Not sure if that's the best way, but it will work https://gist.github.com/miguelmota/904f0fdad34eaac09c5d53098f960c5c#file-struct_custom_unmarshal-go-L15. – georgeok Jun 01 '19 at 20:20

1 Answers1

6

Make another type. It will inherit fields, but not methods. Therefore no infinite loop here.

func (t *T) UnmarshalBSON(b []byte) error {
    type Alias T
    bson.Unmarshal(b, (*Alias)(t))
    // Do something here
    return nil
}
tetafro
  • 477
  • 1
  • 10
  • 15