Help with testing of HTTP handlers & dependency injection

blov · · 468 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I know I should have a code snippet, but I think this is describable without it.</p> <p>Say I have a simple API that allows uploading and downloading of image files. The data stores are a database for associating codes with paths to files, and a filesystem store (so the database says &#34;code aaa is associated with path /foo/bar.jpg).</p> <p>Now, I want to test the handler functions that drive this API, which means I need to mock or inject the data stores. The most simple way of doing this would be dependency injection of a repo-patterned object that supports basic operations like Store(), Fetch(), etc. (enforced via an interface) - except these are http handler functions which take http responsewriter/reader as arguments. No opportunity for easy dependency injection of a data store there that I know of (although maybe I&#39;m wrong there?)</p> <p>I can find lots of advice on the net on testing handlers, and advice on dependency injection, but not both. What&#39;s the right thing to do here?</p> <hr/>**评论:**<br/><br/>classhero: <pre><p>Define your HTTP methods on a struct, like:</p> <p>type HTTPAPI struct { Store Store }</p> <p>func (h *HTTPAPI) NotImplemented(writer http.ResponseWriter, request *http.Request) { h.Store.Whatever() }</p> <p>..and then route to an instantiated version of your struct. HandleFunc takes a function pointer, so you can just do: http.HandleFunc(&#34;/my/path&#34;, myInstantiatedAPI.NotImplemented)</p></pre>

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

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