Hypothetical, I run the API and when the user makes a GET request on the user's resource, I will return the corresponding fields as JSON
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"` }
As you can see, the "Secret" field in "User" has json:"-" . This means that in most operations I would not want to return. In this case, the answer will be
{ "id":1, "Name": "John" }
The field secret is not returned because json:"-" omits the field.
Now I open the route only for the administrator, where I would like to return the secret field. However, this would mean duplication of the user structure.
My current solution looks like this:
type adminUser struct { Id bson.ObjectId `json:"id,omitempty" bson:"_id,omitempty"` Name string `json:"name,omitempty" bson:"name,omitempty"` Secret string `json:"secret,omitempty" bson:"secret,omitempty"` }
Is there any way to insert user into adminUser? Kind of like inheritance:
type adminUser struct { User Secret string `json:"secret,omitempty" bson:"secret,omitempty"` }
This does not currently work, as in this case only the secret secret will be returned.
Note. In a real code base there are several dozen fields. Thus, the cost of duplicating code is high.
The actual mango request is below:
func getUser(w http.ResponseWriter, r *http.Request) { ....omitted code... var user adminUser err := common.GetDB(r).C("users").Find( bson.M{"_id": userId}, ).One(&user) if err != nil { return } common.ServeJSON(w, &user) }