github.com/tilt-dev/tilt@v0.33.15-0.20240515162809-0a22ed45d8a0/internal/testutils/httptest/http_client.go (about) 1 package httptest 2 3 import ( 4 "io" 5 "net/http" 6 "strings" 7 "sync" 8 ) 9 10 type FakeClient struct { 11 requests []http.Request 12 responseCode int 13 responseBody string 14 Err error 15 16 mu sync.Mutex 17 } 18 19 func (fc *FakeClient) Do(req *http.Request) (*http.Response, error) { 20 fc.mu.Lock() 21 defer fc.mu.Unlock() 22 23 fc.requests = append(fc.requests, *req) 24 r := http.Response{ 25 StatusCode: fc.responseCode, 26 Body: io.NopCloser(strings.NewReader(fc.responseBody)), 27 } 28 29 return &r, fc.Err 30 } 31 32 func (fc *FakeClient) SetResponse(s string) { 33 fc.responseCode = http.StatusOK 34 fc.responseBody = s 35 } 36 37 func (fc *FakeClient) ClearRequests() { 38 fc.mu.Lock() 39 defer fc.mu.Unlock() 40 41 fc.requests = nil 42 } 43 44 func (fc *FakeClient) Requests() []http.Request { 45 fc.mu.Lock() 46 defer fc.mu.Unlock() 47 48 ret := append([]http.Request{}, fc.requests...) 49 return ret 50 } 51 52 func NewFakeClient() *FakeClient { 53 return &FakeClient{ 54 responseCode: http.StatusInternalServerError, 55 responseBody: "FakeClient response uninitialized", 56 } 57 } 58 59 func NewFakeClientEmptyJSON() *FakeClient { 60 return &FakeClient{ 61 responseCode: http.StatusOK, 62 responseBody: "{}", 63 } 64 }