URL pattern matching utility for Go servers.
Code tested on Go 1.24.x.
# If using in a project, initialize go module
go mod init myproject
# No third party dependencies needed. Just run the tests or use the function directlygo test -vpackage main
import "fmt"
func main() {
matches := preactIsoUrlPatternMatch("/users/test%40example.com/posts", "/users/:userId/posts", nil)
if matches != nil {
fmt.Printf("User ID: %s\n", matches.Params["userId"]) // Output: test@example.com
}
}func preactIsoUrlPatternMatch(url, route string, matches *Matches) *Matchesurl(string): The URL path to matchroute(string): The route pattern with parametersmatches(*Matches): Optional pre-existing matches to extend
Returns a *Matches struct on success, or nil if no match:
type Matches struct {
Params map[string]string
Rest string
}| Pattern | Description | Example |
|---|---|---|
/users/:id |
Named parameter | {id: "123"} |
/users/:id? |
Optional parameter | {id: ""} |
/files/:path+ |
Required rest parameter | {path: "docs/readme.txt"} |
/static/:path* |
Optional rest parameter | {path: "css/main.css"} |
/static/* |
Anonymous wildcard | {Rest: "/images/logo.png"} |