Uploaded image for project: 'Go Driver'
  1. Go Driver
  2. GODRIVER-2427

Unmarshal Failing With Custom UnmarshalBSON Function and Mismatched pointer/non-pointer typing

    • Type: Icon: Bug Bug
    • Resolution: Fixed
    • Priority: Icon: Unknown Unknown
    • 1.10.0
    • Affects Version/s: None
    • Component/s: None
    • None

      Summary

      Given a custom type whose underlying type is a map and an attached UnmarshalBSON method with a pointer receiver:

      type MyMap map[string]interface{}
      
      func (m *MyMap) UnmarshalBSON(byts []byte) error {
      	//Implementaion not relevant
      	return nil
      }

      Then creating a struct with a field the type of which is the custom type (importantly not a pointer to the type)

      type MyStruct struct {
      	MyMap MyMap
      }

      Any attempt to unmarshal a BSON document into an instance of *MyStruct where the MyMap field in the BSON document is null will cause a panic in bson.DefaultValueDecoders#ValueUnmarshalerDecodeValue

      panic: reflect: reflect.Value.Set using unaddressable value

      Prior to v1.9.0, this code would run through bson.Unmarshal without error.

      Please provide the version of the driver. If applicable, please provide the MongoDB server version and topology (standalone, replica set, or sharded cluster).

      Driver Version: 1.9.0+

      MongoDB version: N/A

      How to Reproduce

      package mainimport (	"fmt"	"go.mongodb.org/mongo-driver/bson")type MyMap map[string]interface{}func (m *MyMap) UnmarshalBSON(byts []byte) error {	// Implementation not relevant	return nil}type MyStruct struct {	MyMap MyMap}func main() {	// Making some BSON so I don't have to craft it by hand	x := &MyStruct{}	byts, err := bson.Marshal(x)	if err != nil {		panic(err)	}	// Immediately unmarshal to show the panic	y := &MyStruct{}	err = bson.Unmarshal(byts, y) // Panic will occur in here	if err != nil {		panic(err)	}}
      

      Additional Background

      N/A

        1. main.go
          0.5 kB
          _aphelps@vailsys.com

            Assignee:
            preston.vasquez@mongodb.com Preston Vasquez
            Reporter:
            aphelps@vailsys.com Anthony Phelps
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: