2021-06-14 19:34:29 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"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-06-20 13:18:02 +00:00
|
|
|
req *http.Request
|
|
|
|
res *http.Response
|
|
|
|
handler http.Handler
|
2021-06-14 19:34:29 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (c *fakeHttpClient) Do(req *http.Request) (*http.Response, error) {
|
2021-06-20 13:18:02 +00:00
|
|
|
if c.handler == nil {
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
rec := httptest.NewRecorder()
|
|
|
|
c.handler.ServeHTTP(rec, req)
|
2021-06-14 19:34:29 +00:00
|
|
|
c.req = req
|
2021-06-20 13:18:02 +00:00
|
|
|
c.res = rec.Result()
|
|
|
|
return c.res, nil
|
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
|
|
|
}
|
|
|
|
|
2021-06-19 06:37:16 +00:00
|
|
|
func getFakeHTTPClient() *fakeHttpClient {
|
|
|
|
return &fakeHttpClient{}
|
2021-06-14 19:34:29 +00:00
|
|
|
}
|