github.com/cloudfoundry-community/cloudfoundry-cli@v6.44.1-0.20240130060226-cda5ed8e89a5+incompatible/integration/helpers/ginkgo_routing_extension.go (about) 1 package helpers 2 3 import ( 4 "errors" 5 "fmt" 6 "net/http" 7 "net/url" 8 "strings" 9 10 . "github.com/onsi/gomega" 11 "github.com/onsi/gomega/ghttp" 12 ) 13 14 type resp struct { 15 status int 16 body []byte 17 } 18 19 var responses map[string]resp 20 var seenRoutes map[string]bool 21 22 func AddHandler(ser *ghttp.Server, method string, pathAndQuery string, status int, body []byte) { 23 u, err := url.Parse(pathAndQuery) 24 if err != nil { 25 panic(err) 26 } 27 if len(responses) == 0 { 28 responses = make(map[string]resp) 29 seenRoutes = make(map[string]bool) 30 } 31 32 responses[key(method, u)] = resp{status, body} 33 34 if !seenRoutes[key(method, u)] { 35 ser.RouteToHandler(method, u.Path, func(w http.ResponseWriter, r *http.Request) { 36 res, ok := responses[key(r.Method, r.URL)] 37 if !ok { 38 Expect(errors.New("Unexpected request: " + key(r.Method, r.URL))).ToNot(HaveOccurred()) 39 } 40 w.WriteHeader(res.status) 41 _, err := w.Write(res.body) 42 Expect(err).ToNot(HaveOccurred()) 43 }) 44 seenRoutes[key(method, u)] = true 45 } 46 } 47 48 func key(method string, url fmt.Stringer) string { 49 return strings.ToLower(method + url.String()) 50 }