<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 "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'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'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("/my/path", myInstantiatedAPI.NotImplemented)</p></pre>
