Note that there are some explanatory texts on larger screens.

plurals
  1. POGolang + MongoDB embedded type (embedding a struct in another struct)
    text
    copied!<p>Hypothetical, I run an API and when a user makes a GET request on the user resource, I will return relevant fields as a JSON</p> <pre><code>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"` } </code></pre> <p>As you can see, the Secret field in User has <code>json:"-"</code>. This implies that in most operation that I would not like to return. In this case, a response would be </p> <pre><code>{ "id":1, "Name": "John" } </code></pre> <p>The field secret will not be returned as <code>json:"-"</code> omits the field.</p> <p>Now, I am openning an admin only route where I would like to return the secret field. However, that would mean duplicating the User struct.</p> <p>My current solution looks like this:</p> <pre><code>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"` } </code></pre> <p>Is there a way to embed User into adminUser? Kind of like inheritance:</p> <pre><code>type adminUser struct { User Secret string `json:"secret,omitempty" bson:"secret,omitempty"` } </code></pre> <p>The above currently does not work, as only the field secret will be returned in this case.</p> <p>Note: In the actual code base, there are few dozens fields. As such, the cost of duplicating code is high. </p> <p>The actual mongo query is below:</p> <pre><code>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(&amp;user) if err != nil { return } common.ServeJSON(w, &amp;user) } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload