Created
April 27, 2017 20:22
-
-
Save ismasan/70e12e99604d824eaa9ebf7073241004 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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