Skip to content

Instantly share code, notes, and snippets.

@avrebarra
Created February 13, 2020 08:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save avrebarra/008ef3e4d6e36704b31e3e601cd3bad3 to your computer and use it in GitHub Desktop.
Save avrebarra/008ef3e4d6e36704b31e3e601cd3bad3 to your computer and use it in GitHub Desktop.
URL Params Matcher - Go
package main
import (
"fmt"
"regexp"
"time"
)
const ParamsRegexPattern = "(:[\\w_]+)"
type URIMatcher struct {
ParamsMatcher *regexp.Regexp
}
func (um *URIMatcher) Check(schema, real string) (b bool) {
wildcardParamSelector := um.ParamsMatcher.ReplaceAllString(schema, ".+?")
return regexp.MustCompile(wildcardParamSelector).MatchString(real)
}
func main() {
parregex, _ := regexp.Compile(ParamsRegexPattern)
um := URIMatcher{ParamsMatcher: parregex}
// Basic Matching
fmt.Println("Matching A:", um.Check("http://coba.com/:data/oke/:data", "http://coba.com/123/oke/something"))
fmt.Println("Matching B:", um.Check("http://coba.com/:data/oke/:data", "http://coba.com/123/oke"))
// Benchmarking Basic
st := time.Now()
for i := 0; i < 1000; i++ {
ok := um.Check("http://coba.com/:data/oasdasdaskeoasdasdaskeoasdasdaskeoasdasdaske/:data/oke/:data/oke/", "http://coba.com/123/oasdasdaskeoasdasdaskeoasdasdaskeoasdasdaske/123/oke/123/oke/")
if !ok {
panic("wrong result!")
}
}
dur := time.Since(st)
fmt.Println("1000 matching done in", dur, "est ops latency", dur/1000)
// Printed Result:
// Matching A: true
// Matching B: false
// 1000 matching done in 23.416141ms est ops latency 23.416µs
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment