Defining a func (idiomatic way) question

polaris · · 464 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I was defining a func getIPAddr() and I just want to ask the internet which method I should use. The point of this function is to get the IP address of a http.Request without the trailing port. E.g. <em>192.168.1.1 will instead of 192.168.1.1:6969.</em></p> <p>Which method is the most idiomatic?</p> <pre><code>func getIPAddr(ip string) string { return strings.Split(ip, &#34;:&#34;)[0] } ip := getIPAddr(r.RemoteAddr) </code></pre> <p><strong>OR</strong></p> <pre><code>func getIPAddr(r *http.Request) string { return strings.Split(r.RemoteAddr, &#34;:&#34;)[0] } ip := getIPAddr(r) </code></pre> <hr/>**评论:**<br/><br/>nemith: <pre><p>One is much easier to write unit tests for. </p> <p>You should also use <a href="https://golang.org/pkg/net/#SplitHostPort" rel="nofollow">https://golang.org/pkg/net/#SplitHostPort</a> instead of writing your own. With IPv6 your function will fail.</p></pre>RalphCorderoy: <pre><p>This isn&#39;t Go specific. Your first version has lower <em>coupling</em> and that is good. The function can be used by a caller that has an <code>ip string</code>, but no http.Request. Sure, they could build a temporary Request just to set RemoteAddr, but then they&#39;re increasing the coupling even more by relying on knowledge of how getIPAddr() works. <a href="https://en.wikipedia.org/wiki/Coupling_(computer_programming)" rel="nofollow">https://en.wikipedia.org/wiki/Coupling_(computer_programming)</a></p></pre>seriouslulz: <pre><p>First one. In general it&#39;s bad style to pass a struct when you only need to access one element, makes testing harder.</p></pre>Saethgokk: <pre><p>Use the first one and please also check is the string is empty or not</p></pre>vorg: <pre><p>For this particular use case, don&#39;t just make the <code>.RemoteAddr</code> field explicit in the calling code, but also skip the function and use:</p> <pre><code>ip := strings.Split(r.RemoteAddr, &#34;:&#34;)[0] </code></pre> <p>The <code>&#34;:&#34;</code> and <code>[0]</code> are the only extra info and don&#39;t need hiding away in a function, just as <code>.RemoteAddr</code> doesn&#39;t.</p></pre>dilap: <pre><p>For a private helper function, either is fine IMO. The second form makes your calling code simpler, which can be a benefit.</p> <p>Contrary some comments, I think they are equally easy to write unit tests for. (&amp;http.Request{RemoteAddr: SOMETESTVALUE} isnt hard.)</p> <p>For a public function I agree the function should take no more than it needs, i.e., prefer the former.</p></pre>

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

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