github.com/hellofresh/janus@v0.0.0-20230925145208-ce8de8183c67/pkg/test/http.go (about) 1 package test 2 3 import ( 4 "bytes" 5 "net/http" 6 "net/http/httptest" 7 8 "github.com/hellofresh/janus/pkg/router" 9 ) 10 11 // Server represents a testing HTTP Server 12 type Server struct { 13 *httptest.Server 14 } 15 16 // NewServer creates a new instance of Server 17 func NewServer(r router.Router) *Server { 18 return &Server{httptest.NewServer(r)} 19 } 20 21 // Do creates a HTTP request to be tested 22 func (s *Server) Do(method string, url string, headers map[string]string) (*http.Response, error) { 23 var u bytes.Buffer 24 u.WriteString(string(s.URL)) 25 u.WriteString(url) 26 27 req, err := http.NewRequest(method, u.String(), nil) 28 if err != nil { 29 return nil, err 30 } 31 32 for headerName, headerValue := range headers { 33 if headerName == "Host" { 34 req.Host = headerValue 35 } else { 36 req.Header.Set(headerName, headerValue) 37 } 38 } 39 40 return http.DefaultClient.Do(req) 41 } 42 43 // Record creates a ResponseRecorder for testing 44 func Record(method string, url string, headers map[string]string, handleFunc http.Handler) (*httptest.ResponseRecorder, error) { 45 req, err := http.NewRequest(method, url, nil) 46 if err != nil { 47 return nil, err 48 } 49 50 for headerName, headerValue := range headers { 51 if headerName == "Host" { 52 req.Host = headerValue 53 } else { 54 req.Header.Set(headerName, headerValue) 55 } 56 } 57 58 w := httptest.NewRecorder() 59 handleFunc.ServeHTTP(w, req) 60 61 return w, nil 62 }