How to avoid type duplication in a JSON api with database?

blov · · 448 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<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 &#34;token&#34; 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&#39;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:&#34;_id&#34; json:&#34;id&#34;` Title string `json:&#34;title&#34;` Options []string `json:&#34;options&#34;` Results map[string]int `json:&#34;results,omitempty&#34;` APIKey string `json:&#34;apikey&#34;` } </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:&#34;-&#34;` 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

448 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传