mirror of
https://github.com/buger/goreplay.git
synced 2024-04-21 12:32:02 +00:00
Merge pull request #127 from jcw9930/url_regexp_rewrite
add regular expression matching to --output-http-rewrite-url
This commit is contained in:
+9
-4
@@ -3,11 +3,12 @@ package main
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type urlRewrite struct {
|
||||
src string
|
||||
src *regexp.Regexp
|
||||
target string
|
||||
}
|
||||
|
||||
@@ -22,14 +23,18 @@ func (r *UrlRewriteMap) Set(value string) error {
|
||||
if len(valArr) < 2 {
|
||||
return errors.New("need both src and target, colon-delimited (ex. /a:/b).")
|
||||
}
|
||||
*r = append(*r, urlRewrite{src: valArr[0], target: valArr[1]})
|
||||
regexp, err := regexp.Compile(valArr[0])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*r = append(*r, urlRewrite{src: regexp, target: valArr[1]})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *UrlRewriteMap) Rewrite(path string) string {
|
||||
for _, f := range *r {
|
||||
if f.src == path {
|
||||
return f.target
|
||||
if f.src.MatchString(path) {
|
||||
return f.src.ReplaceAllString(path, f.target)
|
||||
}
|
||||
}
|
||||
return path
|
||||
|
||||
@@ -4,7 +4,7 @@ import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestUrlRewriteMap(t *testing.T) {
|
||||
func TestUrlRewriteMap_1(t *testing.T) {
|
||||
var url string
|
||||
|
||||
rewrites := UrlRewriteMap{}
|
||||
@@ -15,7 +15,6 @@ func TestUrlRewriteMap(t *testing.T) {
|
||||
}
|
||||
|
||||
url = "/abc"
|
||||
|
||||
if rewrites.Rewrite(url) == url {
|
||||
t.Error("Request url should have been rewritten, wasn't")
|
||||
}
|
||||
@@ -25,3 +24,29 @@ func TestUrlRewriteMap(t *testing.T) {
|
||||
t.Error("Request url should not have been rewritten, was")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUrlRewriteMap_2(t *testing.T) {
|
||||
var url string
|
||||
|
||||
rewrites := UrlRewriteMap{}
|
||||
|
||||
err := rewrites.Set("/v1/user/([^\\/]+)/ping:/v2/user/$1/ping")
|
||||
if err != nil {
|
||||
t.Error("Should not error on /v1/user/([^\\/]+)/ping:/v2/user/$1/ping")
|
||||
}
|
||||
|
||||
url = "/v1/user/joe/ping"
|
||||
if rewrites.Rewrite(url) == url {
|
||||
t.Error("Request url should have been rewritten, wasn't")
|
||||
}
|
||||
|
||||
url = "/v1/user/joe/ping"
|
||||
if rewrites.Rewrite(url) != "/v2/user/joe/ping" {
|
||||
t.Error("Request url should have been rewritten, wasn't")
|
||||
}
|
||||
|
||||
url = "/v1/user/ping"
|
||||
if rewrites.Rewrite(url) != url {
|
||||
t.Error("Request url should not have been rewritten, was")
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user