Detecting empty string state in JSON request

xuanbao · · 352 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<pre><code>type User struct { Bio string Website string } </code></pre> <p>Assume a JSON request that&#39;s attempting to update the user&#39;s Bio to be blank:</p> <pre><code>{ &#34;bio&#34;:&#34;&#34; } </code></pre> <p>But, both <code>bio</code> and <code>website</code> are equal to <code>&#34;&#34;</code>, so it seems difficult to detect if the empty string state is a requested change or not.</p> <p>One possibility would be to use a defined string as an indication to delete:</p> <pre><code>{ &#34;bio&#34;:&#34;[delete]&#34; } if request.Bio == &#34;[delete]&#34; { request.Bio = &#34;&#34; } </code></pre> <p>Is that how people are handling this?</p> <hr/>**评论:**<br/><br/>GentooMonk: <pre><p>You can use *string</p> <p>if req.Bio != nil { bio := *req.Bio } </p></pre>icholy: <pre><p>Add json tags with <code>omitempty</code></p></pre>everdev: <pre><p>That works for writing JSON without empty fields, but I think the pointer is the right solution for detecting empty fields when reading JSON.</p></pre>TheBeasSneeze: <pre><p>Don&#39;t use words in this case, use different http methods: GET, POST, PUT, PATCH and DELETE depending on if you want to get data, add data, update or delete.</p></pre>

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

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