2016-02-25 22:59:38 +00:00
|
|
|
package pathmatch
|
|
|
|
|
2016-02-26 01:18:58 +00:00
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
)
|
|
|
|
|
2016-02-25 22:59:38 +00:00
|
|
|
// Pattern represents a compiled pattern. It is what is returned
|
|
|
|
// from calling either the Compile to MustCompile funcs.
|
|
|
|
//
|
2019-06-21 04:57:03 +00:00
|
|
|
// Pattern provides the Match, FindAndLoad, and MatchNames methods.
|
2016-02-25 22:59:38 +00:00
|
|
|
//
|
|
|
|
// Example Usage:
|
|
|
|
//
|
|
|
|
// pattern, err := pathmath.Compile("/users/{user_id}")
|
|
|
|
// if nil != err {
|
|
|
|
// fmt.Printf("ERROR Compiling: %v\n", err)
|
|
|
|
// return
|
|
|
|
// }
|
|
|
|
//
|
|
|
|
// var userId string
|
|
|
|
//
|
2019-06-21 04:51:32 +00:00
|
|
|
// didMatch, err := pattern.Find("/users/123", userId)
|
2016-02-25 22:59:38 +00:00
|
|
|
// if nil != err {
|
|
|
|
// fmt.Printf("ERROR Matching: %v\n", err)
|
|
|
|
// return
|
|
|
|
// }
|
|
|
|
//
|
|
|
|
// if didMatch {
|
|
|
|
// fmt.Printf("user_id = %q\n", userId)
|
|
|
|
// } else {
|
|
|
|
// fmt.Println("Did not match.")
|
|
|
|
// }
|
2019-06-21 06:28:50 +00:00
|
|
|
type Pattern struct {
|
2016-02-25 22:59:38 +00:00
|
|
|
bits []string
|
|
|
|
names []string
|
|
|
|
namesSet map[string]struct{}
|
|
|
|
fieldTagName string
|
|
|
|
}
|
|
|
|
|
2019-06-21 06:37:46 +00:00
|
|
|
func newPattern(target *Pattern, fieldTagName string) error {
|
|
|
|
if nil == target {
|
|
|
|
return errNilTarget
|
|
|
|
}
|
|
|
|
|
2016-02-25 22:59:38 +00:00
|
|
|
bits := []string{}
|
|
|
|
names := []string{}
|
|
|
|
namesSet := map[string]struct{}{}
|
|
|
|
|
2019-06-21 06:37:46 +00:00
|
|
|
target.bits = bits
|
|
|
|
target.names = names
|
|
|
|
target.namesSet = namesSet
|
|
|
|
target.fieldTagName = fieldTagName
|
2016-02-25 22:59:38 +00:00
|
|
|
|
2019-06-21 06:37:46 +00:00
|
|
|
return nil
|
2016-02-25 22:59:38 +00:00
|
|
|
}
|
2016-02-26 01:18:58 +00:00
|
|
|
|
2019-06-21 06:28:50 +00:00
|
|
|
func (pattern *Pattern) MatchNames() []string {
|
2016-02-26 01:18:58 +00:00
|
|
|
|
|
|
|
return pattern.names
|
|
|
|
}
|
|
|
|
|
2019-06-21 06:28:50 +00:00
|
|
|
func (pattern *Pattern) Glob() string {
|
2016-02-26 01:18:58 +00:00
|
|
|
//@TODO: This shouldn't be executed every time!
|
|
|
|
|
|
|
|
var buffer bytes.Buffer
|
|
|
|
|
|
|
|
for _, bit := range pattern.bits {
|
|
|
|
if wildcardBit == bit {
|
|
|
|
buffer.WriteRune('*')
|
|
|
|
} else {
|
|
|
|
buffer.WriteString(bit)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return buffer.String()
|
|
|
|
}
|