<p>Hi guys,</p>
<p>How do you guys deal with the following:</p>
<ul>
<li>a very similar type (struct) is received both in the HTTP JSON api AND inserted/retrieved from the database;</li>
<li>but the database model has internal IDs (say) while;</li>
<li>the JSON api has an extra field "token" for auth.</li>
</ul>
<p>I have been using 2 similar structs, say:</p>
<ul>
<li>Sensor (for db)</li>
<li>SensorRequest (for api)</li>
</ul>
<p>But I don't like it..</p>
<hr/>**评论:**<br/><br/>8lall0: <pre><p>You can write the commod fields into a struct and then nest them into another struct.</p>
<p>Example:</p>
<pre><code>type CommonFields struct {
Foo string
Blah string
}
type DBFields struct {
ID string
CommonFields
}
type SensorFields struct {
Token string
CommonFields
}
</code></pre></pre>HugoWeb: <pre><p>I think this is the best option in my case.
I had been writing my functions like this:</p>
<pre><code>func (api *Api) someHttpHandler(w http.ResponseWriter, r *http.Request) error {
var input struct {
...
}
var output struct {
...
}
}
</code></pre>
<p>but now I wanted to test and had to make input and output into public types..</p></pre>dcowboy: <pre><p>Here is an example of a struct that gets passed both by JSON and inserted/retrieved into mongodb. The difference being the id field. Mongodb uses _id, my JSON uses id. Not sure if this is what you are looking for.</p>
<pre><code>type poll struct {
ID bson.ObjectId `bson:"_id" json:"id"`
Title string `json:"title"`
Options []string `json:"options"`
Results map[string]int `json:"results,omitempty"`
APIKey string `json:"apikey"`
}
</code></pre></pre>jlrbuellv: <pre><p>You can use tags on your struct definition to tell the json package to ignore or rename certain fields in the struct. The following will output OtherField when encoding to json, but not field.</p>
<pre><code>type t struct {
Field int `json:"-"`
OtherField int
}
</code></pre>
<p>More examples in the <a href="https://golang.org/pkg/encoding/json/#Marshal" rel="nofollow">docs</a></p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传