Embedding a Struct in Another Struct in Golang MongoDB
In this scenario, when a user makes a GET request for the user resource, only relevant fields are returned as JSON. Specifically, the Secret field is excluded due to its json:"-". However, for admin-only requests, returning the secret field is required.
Duplicating the User struct for admin requests is not ideal. The following solution attempts to embed User into adminUser:
type adminUser struct { User Secret string `json:"secret,omitempty" bson:"secret,omitempty"` }
However, this implementation returns only the Secret field, which is not the desired behavior. To achieve the desired result, utilize the bson package's inline flag:
type adminUser struct { User `bson:",inline"` Secret string `json:"secret,omitempty" bson:"secret,omitempty"` }
Note that this may lead to duplicate key errors when reading from the database if both adminUser and User contain the Secret key.
An alternative approach is to remove the Secret field from User and only include it in adminUser. This ensures that writing to the secret field is restricted to admin users.
The above is the detailed content of How to Embed a Struct in Another Struct in Golang for Admin-Only Requests with MongoDB?. For more information, please follow other related articles on the PHP Chinese website!