pathtoregexp

package module
v1.6.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 8, 2022 License: MIT Imports: 7 Imported by: 8

README

Path-to-RegExp

Build Status codecov Go Report Card GoDoc License

Turn a path string such as /user/:name into a regular expression.

Thanks to path-to-regexp which is the original version written in javascript.

Installation

To install Path-to-RegExp package, you need to install Go and set your Go workspace first.

The first need Go installed (version 1.11+ is required), then you can use the below Go command to install Path-to-RegExp.

$ go get -u github.com/soongo/path-to-regexp
Warning

Version 3.2.0, 4.0.0, 4.0.5, 5.0.0 have been removed, please use corresponding version 1.3.2, 1.4.0, 1.4.5, 1.5.0.

Usage

import pathToRegexp "github.com/soongo/path-to-regexp"

// pathToRegexp.PathToRegexp(path, tokens, options) // tokens and options can be nil
// pathToRegexp.Parse(path, options) // options can be nil
// pathToRegexp.Compile(path, options) // options can be nil
// pathToRegexp.MustCompile(path, options) // like Compile but panics if the error is non-nil
// pathToRegexp.Match(path, options) // options can be nil
// pathToRegexp.MustMatch(path, options) // like Match but panics if the error is non-nil
// pathToRegexp.Must(regexp, err) // wraps a call to a function returning (*regexp2.Regexp, error) and panics if the error is non-nil
// pathToRegexp.EncodeURI(str) // encodes characters in URI except `;/?:@&=+$,#`, like javascript's encodeURI
// pathToRegexp.EncodeURIComponent(str) // encodes characters in URI, like javascript's encodeURIComponent
  • path A string, array or slice of strings, or a regular expression with type *github.com/dlclark/regexp2.Regexp.
  • tokens An array to populate with tokens found in the path.
    • token
      • Name The name of the token (string for named or number for index)
      • Prefix The prefix string for the segment (e.g. "/")
      • Suffix The suffix string for the segment (e.g. "")
      • Pattern The RegExp used to match this token (string)
      • Modifier The modifier character used for the segment (e.g. ?)
  • options
    • Sensitive When true the regexp will be case sensitive. (default: false)
    • Strict When true the regexp won't allow an optional trailing delimiter to match. (default: false)
    • End When true the regexp will match to the end of the string. (default: true)
    • Start When true the regexp will match from the beginning of the string. (default: true)
    • Validate When false the function can produce an invalid (unmatched) path. (default: true)
    • Delimiter The default delimiter for segments, e.g. [^/#?] for :named patterns. (default: '/#?')
    • EndsWith Optional character, or list of characters, to treat as "end" characters.
    • Prefixes List of characters to automatically consider prefixes when parsing. (default: ./)
    • Encode How to encode uri. (default: func (uri string, token interface{}) string { return uri })
    • Decode How to decode uri. (default: func (uri string, token interface{}) (string, error) { return uri })
var tokens []pathToRegexp.Token
regexp := pathToRegexp.Must(pathToRegexp.PathToRegexp("/foo/:bar", &tokens, nil))
// regexp: ^\/foo(?:\/([^\/]+?))[\/]?(?=$)
// tokens: [{Name:"bar", Prefix:"/", Suffix:"", Pattern:"[^\\/]+?", Modifier:""}]

Please note: The Regexp returned by path-to-regexp is intended for ordered data (e.g. pathnames, hostnames). It can not handle arbitrarily ordered data (e.g. query strings, URL fragments, JSON, etc). When using paths that contain query strings, you need to escape the question mark (?) to ensure it does not flag the parameter as optional.

Parameters

The path argument is used to define parameters and populate tokens.

Named Parameters

Named parameters are defined by prefixing a colon to the parameter name (:foo).

var tokens []pathToRegexp.Token
regexp := pathToRegexp.Must(pathToRegexp.PathToRegexp("/:foo/:bar", &tokens, nil))
// tokens: [
//   {Name:"foo", Prefix:"/", Suffix:"", Pattern:"[^\\/]+?", Modifier:""},
//   {Name:"bar", Prefix:"/", Suffix:"", Pattern:"[^\\/]+?", Modifier:""}
// ]

match, _ := regexp.FindStringMatch("/test/route")
for _, g := range match.Groups() {
    fmt.Printf("%q ", g.String())
}
fmt.Printf("%d %q\n", match.Index, match)
//=> "/test/route" "test" "route" 0 "/test/route"

Please note: Parameter names must use "word characters" ([A-Za-z0-9_]).

Custom Matching Parameters

Parameters can have a custom regexp, which overrides the default match ([^/]+). For example, you can match digits or names in a path:

var tokens []pathToRegexp.Token
regexpNumbers := pathToRegexp.Must(pathToRegexp.PathToRegexp("/icon-:foo(\\d+).png", &tokens, nil))
// tokens: [{Name:"foo", Prefix:"", Suffix:"", Pattern:"\\d+", Modifier:""}]

match, _ := regexpNumbers.FindStringMatch("/icon-123.png")
for _, g := range match.Groups() {
    fmt.Printf("%q ", g.String())
}
//=> "/icon-123.png" "123"

match, _ := regexpNumbers.FindStringMatch("/icon-abc.png")
fmt.Println(match)
//=> <nil>

tokens = make([]pathToRegexp.Token, 0)
regexpWord := pathToRegexp.Must(pathToRegexp.PathToRegexp("/(user|u)", &tokens, nil))
// tokens: [{Name:0, Prefix:"/", Suffix:"", Pattern:"user|u", Modifier:""}]

match, _ = regexpWord.FindStringMatch("/u")
for _, g := range match.Groups() {
    fmt.Printf("%q ", g.String())
}
//=> "/u" "u"

match, _ = regexpWord.FindStringMatch("users")
fmt.Println(match)
//=> <nil>

Tip: Backslashes need to be escaped with another backslash in JavaScript strings.

Custom Prefix and Suffix

Parameters can be wrapped in {} to create custom prefixes or suffixes for your segment:

regexp := pathToRegexp.Must(pathToRegexp.PathToRegexp("/:attr1?{-:attr2}?{-:attr3}?", nil, nil))

match, _ := regexp.FindStringMatch("/test")
for _, g := range match.Groups() {
    fmt.Printf("%q ", g.String())
}
//=> "/test" "test" "" ""

match, _ = regexp.FindStringMatch("/test-test")
for _, g := range match.Groups() {
    fmt.Printf("%q ", g.String())
}
//=> "/test-test" "test" "test" ""
Unnamed Parameters

It is possible to write an unnamed parameter that only consists of a regexp. It works the same the named parameter, except it will be numerically indexed:

var tokens []pathToRegexp.Token
regexp := pathToRegexp.Must(pathToRegexp.PathToRegexp("/:foo/(.*)", &tokens, nil))
// tokens: [
//   {Name:"foo", Prefix:"/", Suffix:"", Pattern:"[^\\/]+?", Modifier:""}
//   {Name:0, Prefix:"/", Suffix:"", Pattern:".*", Modifier:""}
// ]

match, _ := regexp.FindStringMatch("/test/route")
for _, g := range match.Groups() {
    fmt.Printf("%q ", g.String())
}
fmt.Printf("%d %q\n", match.Index, match)
//=> "/test/route" "test" "route" 0 "/test/route"
Modifiers

Modifiers must be placed after the parameter (e.g. /:foo?, /(test)?, /:foo(test)?, or {-:foo(test)}?).

Optional

Parameters can be suffixed with a question mark (?) to make the parameter optional.

regexp := pathToRegexp.Must(pathToRegexp.PathToRegexp("/:foo/:bar?", nil, nil))
// tokens: [
//   {Name:"foo", Prefix:"/", Suffix:"", Pattern:"[^\\/]+?", Modifier:""}
//   {Name:"bar", Prefix:"/", Suffix:"", Pattern:"[^\\/]+?", Modifier:"?"}
// ]

match, _ := regexp.FindStringMatch("/test")
for _, g := range match.Groups() {
    fmt.Printf("%q ", g.String())
}
fmt.Printf("%d %q\n", match.Index, match)
//=> "/test" "test" "" 0 "/test"

match, _ = regexp.FindStringMatch("/test/route")
for _, g := range match.Groups() {
    fmt.Printf("%q ", g.String())
}
fmt.Printf("%d %q\n", match.Index, match)
//=> "/test/route" "test" "route" 0 "/test/route"

Tip: The prefix is also optional, escape the prefix \/ to make it required.

When dealing with query strings, escape the question mark (?) so it doesn't mark the parameter as optional. Handling unordered data is outside the scope of this library.

regexp := pathToRegexp.Must(pathToRegexp.PathToRegexp("/search/:tableName\\?useIndex=true&term=amazing", nil, nil))

match, _ := regexp.FindStringMatch("/search/people?useIndex=true&term=amazing")
for _, g := range match.Groups() {
    fmt.Printf("%q ", g.String())
}
fmt.Printf("%d %q\n", match.Index, match)
//=> "/search/people?useIndex=true&term=amazing" "people" 0 "/search/people?useIndex=true&term=amazing"

// This library does not handle query strings in different orders
match, _ = regexp.FindStringMatch("/search/people?term=amazing&useIndex=true")
fmt.Println(match)
//=> <nil>
Zero or more

Parameters can be suffixed with an asterisk (*) to denote a zero or more parameter matches.

regexp := pathToRegexp.Must(pathToRegexp.PathToRegexp("/:foo*", nil, nil))
// tokens: [{Name:"foo", Prefix:"/", Suffix:"", Pattern:"[^\\/]+?", Modifier:"*"}]

match, _ := regexp.FindStringMatch("/")
for _, g := range match.Groups() {
    fmt.Printf("%q ", g.String())
}
fmt.Printf("%d %q\n", match.Index, match)
//=> "/" "" 0 "/"

match, _ = regexp.FindStringMatch("/bar/baz")
for _, g := range match.Groups() {
    fmt.Printf("%q ", g.String())
}
fmt.Printf("%d %q\n", match.Index, match)
//=> "/bar/baz" "bar/baz" 0 "/bar/baz"
One or more

Parameters can be suffixed with a plus sign (+) to denote a one or more parameter matches.

regexp := pathToRegexp.Must(pathToRegexp.PathToRegexp("/:foo+", nil, nil))
// tokens: [{Name:"foo", Prefix:"/", Suffix:"", Pattern:"[^\\/]+?", Modifier:"+"}]

match, _ := regexp.FindStringMatch("/")
fmt.Println(match)
//=> nil

match, _ = regexp.FindStringMatch("/bar/baz")
for _, g := range match.Groups() {
    fmt.Printf("%q ", g.String())
}
fmt.Printf("%d %q\n", match.Index, match)
//=> "/bar/baz" "bar/baz" 0 "/bar/baz"
Match

The match function will return a function for transforming paths into parameters:

match := pathToRegexp.MustMatch("/user/:id", &pathToRegexp.Options{Decode: func(str string, token interface{}) (string, error) {
    return pathToRegexp.DecodeURIComponent(str)
}})

match("/user/123")
//=> &pathtoregexp.MatchResult{Path:"/user/123", Index:0, Params:map[interface {}]interface {}{"id":"123"}}

match("/invalid") //=> nil

match("/user/caf%C3%A9")
//=> &pathtoregexp.MatchResult{Path:"/user/caf%C3%A9", Index:0, Params:map[interface {}]interface {}{"id":"café"}}
Parse

The Parse function will return a list of strings and tokens from a path string:

tokens, _ := pathToRegexp.Parse("/route/:foo/(.*)", nil)

fmt.Printf("%#v\n", tokens[0])
//=> "/route"

fmt.Printf("%#v\n", tokens[1])
//=> pathToRegexp.Token{Name:"foo", Prefix:"/", Suffix:"", Pattern:"[^\\/]+?", Modifier:""}

fmt.Printf("%#v\n", tokens[2])
//=> pathToRegexp.Token{Name:0, Prefix:"/", Suffix:"", Pattern:".*", Modifier:""}

Note: This method only works with strings.

Compile ("Reverse" Path-To-RegExp)

The Compile function will return a function for transforming parameters into a valid path:

toPath := pathToRegexp.MustCompile("/user/:id", &pathToRegexp.Options{Encode: func(str string, token interface{}) string {
    return pathToRegexp.EncodeURIComponent(str)
}})

toPath(map[string]int{"id": 123}) //=> "/user/123"
toPath(map[string]string{"id": "café"}) //=> "/user/caf%C3%A9"
toPath(map[string]string{"id": "/"}) //=> "/user/%2F"

toPath(map[string]string{"id": ":/"}) //=> "/user/%3A%2F"

// Without `encode`, you need to make sure inputs are encoded correctly.
falseValue := false
toPathRaw := pathToRegexp.MustCompile("/user/:id", &pathToRegexp.Options{Validate: &falseValue})
toPathRaw(map[string]string{"id": "%3A%2F"}); //=> "/user/%3A%2F"
toPathRaw(map[string]string{"id": ":/"}); //=> "/user/:/"

toPathRepeated := pathToRegexp.MustCompile("/:segment+", nil)

toPathRepeated(map[string]string{"segment": "foo"}) //=> "/foo"
toPathRepeated(map[string][]string{"segment": {"a", "b", "c"}}) //=> "/a/b/c"

toPathRegexp := pathToRegexp.MustCompile("/user/:id(\\d+)", &pathToRegexp.Options{Validate: &falseValue})

toPathRegexp(map[string]int{"id": 123}) //=> "/user/123"
toPathRegexp(map[string]string{"id": "123"}) //=> "/user/123"
toPathRegexp(map[string]string{"id": "abc"}) //=> "/user/abc"

toPathRegexp = pathToRegexp.MustCompile("/user/:id(\\d+)", nil)
toPathRegexp(map[string]string{"id": "abc"}) //=> panic

Note: The generated function will panic on invalid input.

Documentation

Index

Constants

View Source
const Version = "v1.6.4"

Version is the current path-to-regexp's version.

Variables

This section is empty.

Functions

func Compile

func Compile(str string, options *Options) (func(interface{}) (string, error), error)

Compile a string to a template function for the path.

func DecodeURIComponent added in v1.3.2

func DecodeURIComponent(str string) (string, error)

Gets the unencoded version of an encoded component of a Uniform Resource Identifier (URI).

func EncodeURIComponent added in v1.3.2

func EncodeURIComponent(str string) string

EncodeURIComponent encodes a text string as a valid component of a Uniform Resource Identifier (URI).

func Match added in v1.3.2

func Match(path interface{}, options *Options) (func(string) (*MatchResult, error), error)

Match creates path match function from `path-to-regexp` spec.

func Must

func Must(r *regexp2.Regexp, err error) *regexp2.Regexp

Must is a helper that wraps a call to a function returning (*regexp2.Regexp, error) and panics if the error is non-nil. It is intended for use in variable initializations such as

var r = pathtoregexp.Must(pathtoregexp.PathToRegexp("/", nil, nil))

func MustCompile

func MustCompile(str string, options *Options) func(interface{}) (string, error)

MustCompile is like Compile but panics if the expression cannot be compiled. It simplifies safe initialization of global variables.

func MustMatch added in v1.3.2

func MustMatch(path interface{}, options *Options) func(string) (*MatchResult, error)

MustMatch is like Match but panics if err occur in match function.

func Parse

func Parse(str string, options *Options) ([]interface{}, error)

Parse a string for the raw tokens.

func PathToRegexp

func PathToRegexp(path interface{}, tokens *[]Token, options *Options) (*regexp2.Regexp, error)

PathToRegexp normalizes the given path string, returning a regular expression. An empty array can be passed in for the tokens, which will hold the placeholder token descriptions. For example, using `/user/:id`, `tokens` will contain `[{Name: 'id', Delimiter: '/', Optional: false, Repeat: false}]`.

Types

type MatchResult added in v1.3.2

type MatchResult struct {
	// matched url path
	Path string

	// matched start index
	Index int

	// matched params in url
	Params map[interface{}]interface{}
}

MatchResult contains the result of match function

type Options

type Options struct {
	// When true the regexp will be case sensitive. (default: false)
	Sensitive bool

	// When true the regexp won't allow an optional trailing delimiter to match. (default: false)
	Strict bool

	// When true the regexp will match to the end of the string. (default: true)
	End *bool

	// When true the regexp will match from the beginning of the string. (default: true)
	Start *bool

	// When `false` the function can produce an invalid (unmatched) path. (default: `true`)
	Validate *bool

	// Sets the final character for non-ending optimistic matches. (default: `/`)
	Delimiter string

	// Optional character to treat as "end" characters.
	EndsWith string

	// List of characters to automatically consider prefixes when parsing. (default: `./`)
	Prefixes *string

	// how to encode uri
	Encode func(uri string, token interface{}) string

	// how to decode uri
	Decode func(str string, token interface{}) (string, error)
}

Options contains some optional configs

type Token

type Token struct {
	// The name of the token (string for named or number for index)
	Name interface{}

	// The prefix character for the segment (e.g. /)
	Prefix string

	// The suffix string for the segment (e.g. `""`)
	Suffix string

	// The RegExp used to match this token (string)
	Pattern string

	// The modifier character used for the segment (e.g. `?`)
	Modifier string
}

Token is parsed from path. For example, using `/user/:id`, `tokens` will contain `[{Name:'id', Delimiter:'/', Optional:false, Repeat:false}]`

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL