Embedding Types in Golang and MongoDB: An Inheritance-Like Solution
When designing data models for both user interfaces and internal operations, it's common to encounter the need to include sensitive fields that should only be exposed in certain contexts. In Golang, we can utilize the bson package to manage data serialization, including the inclusion or exclusion of specific fields.
Consider the following scenario:
type User struct { Id bson.ObjectId `json:"id,omitempty" bson:"_id,omitempty"` Name string `json:"name,omitempty" bson:"name,omitempty"` Secret string `json:"-,omitempty" bson:"secret,omitempty"` }
In this example, the Secret field is marked with json:"-" and will not be included in the JSON response returned to general users. However, for admin users, we need to access this field. To avoid code duplication, we might consider embedding the User struct into an adminUser struct, like so:
type adminUser struct { User Secret string `json:"secret,omitempty" bson:"secret,omitempty"` }
Unfortunately, this approach won't work as expected, as only the Secret field would be returned, not the User fields.
To overcome this issue, we can leverage the bson:",inline" flag from the bson package. This flag allows us to inherit the fields from the embedded User struct while also defining additional fields:
type adminUser struct { User `bson:",inline"` Secret string `json:"secret,omitempty" bson:"secret,omitempty"` }
While this solves the embedding issue, it introduces a new problem: duplicate key errors when reading data from the database. To resolve this, it's advisable to move the Secret field out of the User struct and into the adminUser struct. This ensures that the Secret field is only exposed in the adminUser context. In this way, you can maintain a consistent data model while managing the exposure of sensitive fields based on user roles.
The above is the detailed content of How to Achieve Inheritance-Like Behavior with Embedded Types in Golang and MongoDB?. For more information, please follow other related articles on the PHP Chinese website!