MCPcopy Index your code
hub / github.com/labstack/echo / TestProxyRewriteRegex

Function TestProxyRewriteRegex

middleware/proxy_test.go:261–319  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

259}
260
261func TestProxyRewriteRegex(t *testing.T) {
262 // Setup
263 receivedRequestURI := make(chan string, 1)
264 upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
265 // RequestURI is the unmodified request-target of the Request-Line (RFC 7230, Section 3.1.1) as sent by the client to a server
266 // we need unmodified target to see if we are encoding/decoding the url in addition to rewrite/replace logic
267 // if original request had `%2F` we should not magically decode it to `/` as it would change what was requested
268 receivedRequestURI <- r.RequestURI
269 }))
270 defer upstream.Close()
271 tmpUrL, _ := url.Parse(upstream.URL)
272 rrb := NewRoundRobinBalancer([]*ProxyTarget{{Name: "upstream", URL: tmpUrL}})
273
274 // Rewrite
275 e := echo.New()
276 e.Use(ProxyWithConfig(ProxyConfig{
277 Balancer: rrb,
278 Rewrite: map[string]string{
279 "^/a/*": "/v1/$1",
280 "^/b/*/c/*": "/v2/$2/$1",
281 "^/c/*/*": "/v3/$2",
282 },
283 RegexRewrite: map[*regexp.Regexp]string{
284 regexp.MustCompile("^/x/.+?/(.*)"): "/v4/$1",
285 regexp.MustCompile("^/y/(.+?)/(.*)"): "/v5/$2/$1",
286 },
287 }))
288
289 testCases := []struct {
290 requestPath string
291 statusCode int
292 expectPath string
293 }{
294 {"/unmatched", http.StatusOK, "/unmatched"},
295 {"/a/test", http.StatusOK, "/v1/test"},
296 {"/b/foo/c/bar/baz", http.StatusOK, "/v2/bar/baz/foo"},
297 {"/c/ignore/test", http.StatusOK, "/v3/test"},
298 {"/c/ignore1/test/this", http.StatusOK, "/v3/test/this"},
299 {"/x/ignore/test", http.StatusOK, "/v4/test"},
300 {"/y/foo/bar", http.StatusOK, "/v5/bar/foo"},
301 // NB: fragment is not added by golang httputil.NewSingleHostReverseProxy implementation
302 // $2 = `bar?q=1#frag`, $1 = `foo`. replaced uri = `/v5/bar?q=1#frag/foo` but httputil.NewSingleHostReverseProxy does not send `#frag/foo` (currently)
303 {"/y/foo/bar?q=1#frag", http.StatusOK, "/v5/bar?q=1"},
304 }
305
306 for _, tc := range testCases {
307 t.Run(tc.requestPath, func(t *testing.T) {
308 targetURL, _ := url.Parse(tc.requestPath)
309 req := httptest.NewRequest(http.MethodGet, targetURL.String(), nil)
310 rec := httptest.NewRecorder()
311
312 e.ServeHTTP(rec, req)
313
314 actualRequestURI := <-receivedRequestURI
315 assert.Equal(t, tc.expectPath, actualRequestURI)
316 assert.Equal(t, tc.statusCode, rec.Code)
317 })
318 }

Callers

nothing calls this directly

Calls 6

NewRoundRobinBalancerFunction · 0.85
ProxyWithConfigFunction · 0.85
ServeHTTPMethod · 0.80
CloseMethod · 0.45
UseMethod · 0.45
StringMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…