<p>So, I'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'd have to go into more detail about what packages/frameworks you'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'm using "gorilla/mux" and "strconv". 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'm thinking something like this: if { int.Ip == nil (panic "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="https://golang.org/pkg/net/http/#Error" 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大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传