| 1 | package test |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "io/ioutil" |
| 6 | "net/http" |
| 7 | "net/http/httptest" |
| 8 | ) |
| 9 | |
| 10 | type httpMockResponse struct { |
| 11 | http.Response |
| 12 | Data []byte |
| 13 | } |
| 14 | |
| 15 | func (r *httpMockResponse) ServeHTTP(http.ResponseWriter, *http.Request) { |
| 16 | } |
| 17 | |
| 18 | type HTTPMockTransport struct { |
| 19 | mux *http.ServeMux |
| 20 | } |
| 21 | |
| 22 | func (t *HTTPMockTransport) Clear() { |
| 23 | t.mux = http.NewServeMux() |
| 24 | } |
| 25 | |
| 26 | func (t *HTTPMockTransport) Add(path string, res *http.Response, data []byte) { |
| 27 | if t.mux == nil { |
| 28 | t.mux = http.NewServeMux() |
| 29 | } |
| 30 | |
| 31 | t.mux.Handle(path, &httpMockResponse{ |
| 32 | Response: *res, |
| 33 | Data: data, |
| 34 | }) |
| 35 | } |
| 36 | |
| 37 | func (t *HTTPMockTransport) AddHandlerFunc(path string, hf http.HandlerFunc) { |
| 38 | if t.mux == nil { |
| 39 | t.mux = http.NewServeMux() |
| 40 | } |
| 41 | |
| 42 | t.mux.HandleFunc(path, hf) |
| 43 | } |
| 44 | |
| 45 | func (t *HTTPMockTransport) RoundTrip(req *http.Request) (*http.Response, error) { |
| 46 | h, ptn := t.mux.Handler(req) |
| 47 | var res *httpMockResponse |
| 48 | if ptn == "" { |
| 49 | res = &httpMockResponse{ |
| 50 | Response: http.Response{ |
| 51 | StatusCode: 404, |
| 52 | }, |
| 53 | } |
| 54 | } else { |
| 55 | var ok bool |
| 56 | res, ok = h.(*httpMockResponse) |
| 57 | if !ok { |
| 58 | rw := httptest.NewRecorder() |
| 59 | h.ServeHTTP(rw, req) |
| 60 | res := &http.Response{ |
| 61 | StatusCode: rw.Code, |
| 62 | Header: rw.HeaderMap, |
| 63 | Body: ioutil.NopCloser(bytes.NewReader(rw.Body.Bytes())), |
| 64 | } |
| 65 | return res, nil |
| 66 | } |
| 67 | } |
| 68 | res.Response.Body = ioutil.NopCloser(bytes.NewReader(res.Data)) |
| 69 | return &res.Response, nil |
| 70 | } |