I have a struct called Article
which has a field called Image
. Per default Image
has value nil
. As Image
should be only persisted as Image.Id
to database I use the bson.BSONGetter
, bson.BSONSetter
and json.Marshaler
interfaces to fake this behavior.
However internally it is possible to use Image
as an io.ReadWriteCloser
if I load a file onto this with some other helper.
package main
import (
"io"
"fmt"
"gopkg.in/mgo.v2"
)
type Article struct {
Name string
Image *Image
}
type Image struct {
Id interface{}
io.ReadWriteCloser
}
func (i *Image) SetBSON(r bson.Raw) error {
i = &Image{}
return r.Marshal(i.Id)
}
func (i *Image) GetBSON() (interface{}, error) {
return i.Id
}
func (i *Image) MarshalJSON() ([]byte, error) {
return json.Marshal(i.Id)
}
The problem with this approach now is that it is not possible to initialize Image
in Image.SetBSON
as Image
is nil
.