Last active
May 8, 2021 12:31
-
-
Save canhlinh/af7f47d7acac48dace3bac562c533a6f to your computer and use it in GitHub Desktop.
Simple parser for URL pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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