Encoding concrete type for a custom registry

I’m building my custom registry

func NewRegistry() *bsoncodec.Registry {
	r := bsoncodec.NewRegistry()

       myType := reflect.TypeOf(types.myType{})

	r.RegisterTypeEncoder(myType, bsoncodec.ValueEncoderFunc(myTpeEncodeValue))
	r.RegisterTypeDecoder(myType, bsoncodec.ValueDecoderFunc(myTypeDecodeValue))
	return r
}

myType is type myType []byte

I have a library on my side to marshal/unmarshal bytes to get a defined struct.

Once inside the encode func I call my Unmarshal I get the concrete struct that look like

type MyStruct struct {
  Foo []string
  ID string
}

My question is how can I encode this struct?

Should I use call repeadetely inside encode func, the bsonrw.ValueWriter so I can write separately each field?

@Salvatore_Mazzarino welcome and thanks for the question! Here is a Go Playground example of how to implement a ValueEncoder that does something similar to you’re describing.

However, you should strongly consider the much simpler approach of adding a MarshalBSON method on myType (so it implements the bson.Marshaler interface) instead of using a Registry. Here is a Go Playground example of a MarshalBSON method that does something similar to what you’re describing.

Another tip: If you end up using a Registry, use bson.NewRegistry to create a registry with the default codecs registered, instead of bsoncodec.NewRegistry (which creates an empty registry).