Skip to content

Instantly share code, notes, and snippets.

@canhlinh
Last active May 8, 2021 12:31
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 canhlinh/af7f47d7acac48dace3bac562c533a6f to your computer and use it in GitHub Desktop.
Save canhlinh/af7f47d7acac48dace3bac562c533a6f to your computer and use it in GitHub Desktop.
Simple parser for URL pattern
package main
import (
"fmt"
"regexp"
)
var reResVars = regexp.MustCompile(`\\\{[^{}]+\\\}`)
func main() {
matched, err := parsePathParams("https://google.com/user/7878/documents/123/aa", "/user/{user_id}/documents/{document_id}")
if err != nil {
panic(err)
}
for key, value := range matched {
if key == "" {
continue
}
fmt.Printf("%s:%s\n", key, value)
}
}
func parsePathParams(rawurl string, pattern string) (map[string]string, error) {
pattern = regexp.QuoteMeta(pattern)
pattern = reResVars.ReplaceAllStringFunc(pattern, func(s string) string {
group := s[2 : len(s)-2]
return "(?P<" + group + ">[a-zA-Z0-9-]+)"
})
re := regexp.MustCompile(pattern)
matches := re.FindStringSubmatch(rawurl)
names := re.SubexpNames()
m := map[string]string{}
for i, match := range matches {
m[names[i]] = match
}
return m, nil
}
// https://play.golang.org/p/pje8t-IqI7s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment