Making a struct require by default.

polaris · · 177 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>So, I&#39;m making a rest api that handles JSON data. However I have yet to found an option that makes a specific value (lets say the ip of the sender) required. So if no IP is received from the sender it will just return an error. Any help would be appreciated. </p> <hr/>**评论:**<br/><br/>BS_in_BS: <pre><p>you&#39;d have to go into more detail about what packages/frameworks you&#39;re using.</p> <p>One way to do it could be to use tag on struct fields with some reflection.</p></pre>JonTargaryanTheFirst: <pre><p>Ok. The main packages I&#39;m using &#34;gorilla/mux&#34; and &#34;strconv&#34;. So basically I have a Route struct which fetches Ip, Id, Time etc. (currently only works with postman injection). And I would like it to return an error if the Ip field is omitted empty. I&#39;m thinking something like this: if { int.Ip == nil (panic &#34;Ip field required)}.</p></pre>BS_in_BS: <pre><p>the quickest way is to instead of a <code>panic</code> call, use <a href="" rel="nofollow">http.Error</a> and return a 400 response with your error message.</p></pre>koalefant: <pre><p>Implement the json Unmarshaler interface, it’s something like UnmarshalJSON(b []byte) error</p> <p>If ip is not there just return an error</p> <p>You can even do verifications on it to make sure it’s within a certain range or that it’s valid syntax</p></pre>

入群交流(和以上内容无关):Go中文网 QQ 交流群:729884609 或加微信入微信群:274768166 备注:入群;关注公众号:Go语言中文网

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