pathtoregexp

package module
v5.0.0 Latest Latest
Warning

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

Go to latest
Published: Jan 9, 2020 License: MIT Imports: 8 Imported by: 0

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

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 character for the segment (e.g. /)
      • Delimiter The delimiter for the segment (same as prefix or default delimiter)
      • Optional Indicates the token is optional (boolean)
      • Repeat Indicates the token is repeated (boolean)
      • Pattern The RegExp used to match this token (string)
  • options
    • Sensitive When true the regexp will be case sensitive. (default: false)
    • Strict When true the regexp allows 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)
    • Delimiter The default delimiter for segments. (default: '/')
    • EndsWith Optional character, or list of characters, to treat as "end" characters.
    • Whitelist List of characters to consider delimiters when parsing. (default: nil, any character)
    • 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 { return uri })
var tokens []pathToRegexp.Token
regexp := pathToRegexp.Must(pathToRegexp.PathToRegexp("/foo/:bar", &tokens, nil))
// regexp: ^\/foo\/([^\/]+?)(?:\/)?$
// tokens: [{Name:"bar", Prefix:"/", Delimiter:"/", Optional:false, Repeat:false, Pattern:"[^\\/]+?"}}]

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).

Parameters

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

Named Parameters

Named parameters are defined by prefixing a colon to the parameter name (:foo). By default, the parameter will match until the next prefix (e.g. [^/]+).

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

match, err := 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_]).

Parameter Modifiers
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:"/", Delimiter:"/", Optional:false, Repeat:false, Pattern:"[^\\/]+?"},
//   {Name:"bar", Prefix:"/", Delimiter:"/", Optional:true, Repeat:false, Pattern:"[^\\/]+?"}
// ]

match, err := 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, err = 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.

Zero or more

Parameters can be suffixed with an asterisk (*) to denote a zero or more parameter matches. The prefix is used for each match.

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

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

match, err = 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. The prefix is used for each match.

regexp := pathToRegexp.Must(pathToRegexp.PathToRegexp("/:foo+", nil, nil))
// tokens: [{Name:"foo", Prefix:"/", Delimiter:"/", Optional:false, Repeat:true, Pattern:"[^\\/]+?"}]

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

match, err = 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"
Unnamed Parameters

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

regexp := pathToRegexp.Must(pathToRegexp.PathToRegexp("/:foo/(.*)", nil, nil))
// tokens: [
//   {Name:"foo", Prefix:"/", Delimiter:"/", Optional:false, Repeat:false, Pattern:"[^\\/]+?"},
//   {Name:0, Prefix:"/", Delimiter:"/", Optional:false, Repeat:false, Pattern:".*"}
// ]

match, err := 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"
Custom Matching Parameters

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

regexpNumbers := pathToRegexp.Must(pathToRegexp.PathToRegexp("/icon-:foo(\\d+).png", nil, nil))
// tokens: {Name:"foo", Prefix:"-", Delimiter:"-", Optional:false, Repeat:false, Pattern:"\\d+"}

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

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

regexpWord := pathToRegexp.Must(pathToRegexp.PathToRegexp("/(user|u)", nil, nil))
// tokens: {Name:0, Prefix:"/", Delimiter:"/", Optional:false, Repeat:false, Pattern:"user|u"}

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

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

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

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 {
    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:"/", Delimiter:"/", Optional:false, Repeat:false, Pattern:"[^\\/]+?"}

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

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. It will do all necessary checks to ensure the generated path is valid. This method only works with strings.

Documentation

Index

Constants

View Source
const Version = "v5.0.0"

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

Variables

This section is empty.

Functions

func Compile

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

Compile a string to a template function for the path.

func DecodeURIComponent

func DecodeURIComponent(str string) string

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

func EncodeURIComponent

func EncodeURIComponent(str string) string

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

func Match

func Match(path interface{}, o *Options) (func(string) *MatchResult, 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, o *Options) func(interface{}) string

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

func MustMatch

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

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

func Parse

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

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

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 allows 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

	Validate *bool

	// The default delimiter for segments. (default: '/')
	Delimiter string

	// Optional character, or list of characters, to treat as "end" characters.
	EndsWith interface{}

	// List of characters to consider delimiters when parsing. (default: nil, any character)
	Whitelist []string

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

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

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 delimiter for the segment (same as prefix or default delimiter)
	Delimiter string

	// Indicates the token is optional (boolean)
	Optional bool

	// Indicates the token is repeated (boolean)
	Repeat bool

	// The RegExp used to match this token (string)
	Pattern 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