Making a struct require by default.

polaris · 2017-10-10 00:00:03 · 685 次点击    
这是一个分享于 2017-10-10 00:00:03 的资源,其中的信息可能已经有所发展或是发生改变。

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.


评论:

BS_in_BS:

you'd have to go into more detail about what packages/frameworks you're using.

One way to do it could be to use tag on struct fields with some reflection.

JonTargaryanTheFirst:

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)}.

BS_in_BS:

the quickest way is to instead of a panic call, use http.Error and return a 400 response with your error message.

koalefant:

Implement the json Unmarshaler interface, it’s something like UnmarshalJSON(b []byte) error

If ip is not there just return an error

You can even do verifications on it to make sure it’s within a certain range or that it’s valid syntax


入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

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