pathmatch.Pattern.Match()

master
Charles Iliya Krempeaux 2019-06-21 15:26:35 -07:00
parent 5d60552f12
commit 7bad8c950e
2 changed files with 130 additions and 0 deletions

23
pattern_match.go 100644
View File

@ -0,0 +1,23 @@
package pathmatch
// Match returns true if path matches the compiled pattern, else returns false if it doesn't match.
func (receiver *Pattern) Match(path string) (bool, error) {
if nil == receiver {
return false, errNilReceiver
}
//@TODO: Is it a good idea to be dynamically creating this?
//@TODO: Also, can the struct fields be put in here directly instead?
args := []interface{}{}
numNames := len(receiver.MatchNames())
for i:=0; i<numNames; i++ {
args = append(args, new(string))
}
found, err := receiver.Find(path, args...)
if nil != err {
return false, err
}
return found, nil
}

View File

@ -0,0 +1,107 @@
package pathmatch_test
import (
"github.com/reiver/go-pathmatch"
"testing"
)
func TestPatternMatch(t *testing.T) {
tests := []struct{
Pattern string
Path string
Expected bool
}{
{
Pattern: "/v1/help",
Path: "/v1/help",
Expected: true,
},
{
Pattern: "/v1/help",
Path: "/v2/help",
Expected: false,
},
{
Pattern: "/v1/help",
Path: "/v2/HELP",
Expected: false,
},
{
Pattern: "/v1/help",
Path: "/v1/apple",
Expected: false,
},
{
Pattern: "/v1/help",
Path: "/v1/banana",
Expected: false,
},
{
Pattern: "/v1/help",
Path: "/v1/cherry",
Expected: false,
},
{
Pattern: "/v1/user/{user_id}/contact/{contact_type}",
Path: "/v1/user/123/contact/e-mail",
Expected: true,
},
{
Pattern: "/v1/user/{user_id}/contact/{contact_type}",
Path: "/v2/user/123/contact/e-mail",
Expected: false,
},
{
Pattern: "/v1/user/{user_id}/contact/{contact_type}",
Path: "/v2/user/123/contact/e-mail",
Expected: false,
},
{
Pattern: "/v1/company/{company_name}",
Path: "/v1/company/acme",
Expected: true,
},
{
Pattern: "/v1/company/{company_name}",
Path: "/v2/company/acme",
Expected: false,
},
{
Pattern: "/v1/company/{company_name}",
Path: "/v1/user/acme",
Expected: false,
},
{
Pattern: "/v1/company/{company_name}",
Path: "/v1/COMPANY/acme",
Expected: false,
},
}
for testNumber, test := range tests {
var pattern pathmatch.Pattern
if err := pathmatch.CompileTo(&pattern, test.Pattern); nil != err {
t.Errorf("For test #%d, did not expect an error, but actually got one: (%T) %q", testNumber, err, err)
continue
}
matched, err := pattern.Match(test.Path)
if nil != err {
t.Errorf("For test #%d, did not expect an error, but actually got one: (%T) %q", testNumber, err, err)
continue
}
if expected, actual := test.Expected, matched; expected != actual {
t.Errorf("For test #%d, expected %t, but actually got %t.", testNumber, expected, actual)
continue
}
}
}