Skip to content

Instantly share code, notes, and snippets.

@ismasan
Created April 27, 2017 20:22
Show Gist options
  • Select an option

  • Save ismasan/70e12e99604d824eaa9ebf7073241004 to your computer and use it in GitHub Desktop.

Select an option

Save ismasan/70e12e99604d824eaa9ebf7073241004 to your computer and use it in GitHub Desktop.
package client
import (
"net/http"
"net/http/httptest"
)
// A *http.Client that talks directly to an http.Handler
// instead of going over the network
// Useful to testing your Go APIs with the same client you provide to your users
func NewTestHTTPClient(server http.Handler) *http.Client {
tr := &inProcessTransport{
server: server,
}
return &http.Client{Transport: tr}
}
type inProcessTransport struct {
server http.Handler
}
func (t *inProcessTransport) RoundTrip(req *http.Request) (*http.Response, error) {
testReq := httptest.NewRequest(req.Method, req.URL.String(), req.Body)
copyHeader(testReq.Header, req.Header)
w := httptest.NewRecorder()
t.server.ServeHTTP(w, testReq)
return w.Result(), nil
}
func copyHeader(dst, src http.Header) {
for k, vv := range src {
for _, v := range vv {
dst.Add(k, v)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment