Skip to content

Instantly share code, notes, and snippets.

@hsluoyz
Last active September 28, 2019 07:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hsluoyz/e2368ce97b8239b4805ba13d64e52deb to your computer and use it in GitHub Desktop.
Save hsluoyz/e2368ce97b8239b4805ba13d64e52deb to your computer and use it in GitHub Desktop.
// KeyMatch4 determines whether key1 matches the pattern of key2 (similar to RESTful path), key2 can contain a *.
// Besides what KeyMatch3 does, KeyMatch4 can also match repeated patterns:
// "/parent/123/child/123" matches "/parent/{id}/child/{id}"
// "/parent/123/child/456" does not match "/parent/{id}/child/{id}"
// But KeyMatch3 will match both.
func KeyMatch4(key1 string, key2 string) bool {
key2 = strings.Replace(key2, "/*", "/.*", -1)
tokenMap := map[string]int{}
j := -1
for i, c := range key2 {
if c == '{' {
j = i
} else if c == '}' {
token := key2[j:i+1]
if cnt, ok := tokenMap[token]; !ok {
tokenMap[token] = 1
} else {
tokenMap[token] = cnt + 1
}
}
}
i := 1
for token, cnt := range tokenMap {
if cnt == 1 {
key2 = strings.Replace(key2, token, "[^/]+", 1)
} else {
key2 = strings.Replace(key2, token, "([^/]+)", 1)
key2 = strings.ReplaceAll(key2, token, fmt.Sprintf("\\%d", i))
i += 1
}
}
return RegexMatch(key1, "^"+key2+"$")
}
// KeyMatch4Func is the wrapper for KeyMatch4.
func KeyMatch4Func(args ...interface{}) (interface{}, error) {
name1 := args[0].(string)
name2 := args[1].(string)
return bool(KeyMatch4(name1, name2)), nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment