Couple of questions about web apps in Go

blov · · 441 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>1) Is there a particular reason why the Handler interface has the io.Reader (edit: oops I mean, http.Request) as a symbol but not the ResponseWriter? I&#39;m really just curious</p> <p>2) What is standard practice in go for exposing application-level variables to handlers? I&#39;ve seen this done with context for some things like the current user and the session, but what about the gorilla Router for accessing named routes? Make it a global variable or add it to context?</p> <hr/>**评论:**<br/><br/>seufert: <pre><ol> <li>Request (value type, therefore the pointer) is a struct, ReponseWriter (reference type) is an interface.</li> <li>I don&#39;t think that there is really a standard practice - have seen it more or less all: Global Variables, Common structs (often called controllers) for a bunch of handlers, Context...</li> </ol></pre>boydatw: <pre><p>Is it usually better to take in structs as pointers to structs in arguments to methods? In what cases wouldn&#39;t you use a pointer (besides when you are taking an interface)?</p> <p>Coming from a language (Ruby) that doesn&#39;t have pointers so I don&#39;t have any intuition there.</p></pre>seufert: <pre><p>If you pass a struct by value (so not as a pointer), then 1. You have some overhead since it will be copied. For larger structs that overhead can be significant 2. If you change the struct you passed by value if will be only changed in the function/method and not outside. So it&#39;s also the question if you want work on a copy or not.</p> <p>See the anyway recommended Go-Tour: <a href="https://tour.golang.org/methods/3" rel="nofollow">https://tour.golang.org/methods/3</a></p></pre>daveddev: <pre><p>1 - http.ResponseWriter is an interface and http.Request is a struct. It is uncommon to need a pointer to an interface, and a pointer to an instance of a struct is common.</p> <p>2 - Request-scoped variables should reside in a request context like net/context (a context field is being added to the http.Request type in 1.7). Application-scoped variables, can be in globals for small apps, or within a custom struct with handlers as methods for larger apps.</p> <p>Adding to this: For pulling parameters from routes, I use <a href="http://github.com/codemodus/parth" rel="nofollow">http://github.com/codemodus/parth</a>. For passing a request context, I use <a href="http://github.com/codenodus/chain" rel="nofollow">http://github.com/codenodus/chain</a>. For application-scoped variables, I make a type with the relevant fields, and add handler methods to it.</p></pre>

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

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