2021-06-14 19:34:29 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2021-12-07 17:23:57 +00:00
|
|
|
"io"
|
2021-06-14 19:34:29 +00:00
|
|
|
"net/http"
|
2021-06-20 13:18:02 +00:00
|
|
|
"net/http/httptest"
|
2021-06-14 19:34:29 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type fakeHttpClient struct {
|
2021-12-07 17:23:57 +00:00
|
|
|
*http.Client
|
2021-06-20 13:18:02 +00:00
|
|
|
req *http.Request
|
|
|
|
res *http.Response
|
|
|
|
handler http.Handler
|
2021-06-14 19:34:29 +00:00
|
|
|
}
|
|
|
|
|
2021-12-07 17:23:57 +00:00
|
|
|
func newFakeHttpClient() *fakeHttpClient {
|
|
|
|
fc := &fakeHttpClient{}
|
|
|
|
fc.Client = &http.Client{
|
|
|
|
Transport: &handlerRoundTripper{
|
|
|
|
handler: http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
|
|
|
|
fc.req = r
|
|
|
|
if fc.handler != nil {
|
|
|
|
rec := httptest.NewRecorder()
|
|
|
|
fc.handler.ServeHTTP(rec, r)
|
|
|
|
fc.res = rec.Result()
|
|
|
|
// Copy the headers from the response recorder
|
|
|
|
for k, v := range rec.Header() {
|
|
|
|
rw.Header()[k] = v
|
|
|
|
}
|
|
|
|
// Copy result status code and body
|
|
|
|
rw.WriteHeader(fc.res.StatusCode)
|
2021-12-14 16:38:36 +00:00
|
|
|
_, _ = io.Copy(rw, rec.Body)
|
2021-12-07 17:23:57 +00:00
|
|
|
}
|
|
|
|
}),
|
|
|
|
},
|
2021-06-20 13:18:02 +00:00
|
|
|
}
|
2021-12-07 17:23:57 +00:00
|
|
|
return fc
|
2021-06-14 19:34:29 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (c *fakeHttpClient) clean() {
|
|
|
|
c.req = nil
|
|
|
|
c.res = nil
|
2021-06-20 13:18:02 +00:00
|
|
|
c.handler = nil
|
2021-06-14 19:34:29 +00:00
|
|
|
}
|
|
|
|
|
2021-06-20 13:18:02 +00:00
|
|
|
func (c *fakeHttpClient) setHandler(handler http.Handler) {
|
2021-06-14 19:34:29 +00:00
|
|
|
c.clean()
|
2021-06-20 13:18:02 +00:00
|
|
|
c.handler = handler
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *fakeHttpClient) setFakeResponse(statusCode int, body string) {
|
|
|
|
c.setHandler(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
|
|
|
|
rw.WriteHeader(statusCode)
|
2021-06-23 17:20:50 +00:00
|
|
|
_, _ = rw.Write([]byte(body))
|
2021-06-20 13:18:02 +00:00
|
|
|
}))
|
2021-06-14 19:34:29 +00:00
|
|
|
}
|