From 750283cefd42894a5fa4c550b42c45fe19c3bd63 Mon Sep 17 00:00:00 2001 From: Vasiliy Tolstov Date: Wed, 29 Apr 2020 15:23:10 +0300 Subject: [PATCH] api/router: avoid unneeded loops and fix path match (#1594) * api/router: avoid unneeded loops and fix path match * if match found in google api path syntax, not try pcre loop * if path is not ending via $ sign, append it to pcre to avoid matching other strings like /api/account/register can be matched to /api/account * api: add tests and validations Signed-off-by: Vasiliy Tolstov --- registry.go | 35 +++++++++++++++++++++++------------ 1 file changed, 23 insertions(+), 12 deletions(-) diff --git a/registry.go b/registry.go index b5ab4d8..478a2e4 100644 --- a/registry.go +++ b/registry.go @@ -187,10 +187,13 @@ func (r *registryRouter) store(services []*registry.Service) { for _, p := range ep.Endpoint.Path { var pcreok bool - pcrereg, err := regexp.CompilePOSIX(p) - if err == nil { - cep.pcreregs = append(cep.pcreregs, pcrereg) - pcreok = true + + if p[0] == '^' && p[len(p)-1] != '$' { + pcrereg, err := regexp.CompilePOSIX(p) + if err == nil { + cep.pcreregs = append(cep.pcreregs, pcrereg) + pcreok = true + } } rule, err := util.Parse(p) @@ -359,6 +362,9 @@ func (r *registryRouter) Endpoint(req *http.Request) (*api.Service, error) { } continue } + if logger.V(logger.DebugLevel, logger.DefaultLogger) { + logger.Debugf("api gpath match %s = %v", path, pathreg) + } pMatch = true ctx := req.Context() md, ok := metadata.FromContext(ctx) @@ -373,16 +379,21 @@ func (r *registryRouter) Endpoint(req *http.Request) (*api.Service, error) { break } - // 4. try path via pcre path matching - for _, pathreg := range cep.pcreregs { - if !pathreg.MatchString(req.URL.Path) { - if logger.V(logger.DebugLevel, logger.DefaultLogger) { - logger.Debugf("api pcre path not match %s != %v", path, pathreg) + if !pMatch { + // 4. try path via pcre path matching + for _, pathreg := range cep.pcreregs { + if !pathreg.MatchString(req.URL.Path) { + if logger.V(logger.DebugLevel, logger.DefaultLogger) { + logger.Debugf("api pcre path not match %s != %v", path, pathreg) + } + continue } - continue + if logger.V(logger.DebugLevel, logger.DefaultLogger) { + logger.Debugf("api pcre path match %s != %v", path, pathreg) + } + pMatch = true + break } - pMatch = true - break } if !pMatch {