Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 93 additions & 0 deletions helpers/regex_maker.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package helpers

import (
"bytes"
"fmt"
"regexp"
"strings"
)

func GetRegexForPath(tpl string) (*regexp.Regexp, error) {
Comment thread
Rishabh-Daga marked this conversation as resolved.
// Check if it is well-formed.
idxs, errBraces := BraceIndices(tpl)
if errBraces != nil {
return nil, errBraces
}

// Backup the original.
template := tpl

// Now let's parse it.
defaultPattern := "[^/]*"

pattern := bytes.NewBufferString("^")
var end int

for i := 0; i < len(idxs); i += 2 {

// Set all values we are interested in.
raw := tpl[end:idxs[i]]
end = idxs[i+1]
parts := strings.SplitN(tpl[idxs[i]+1:end-1], ":", 2)
name := parts[0]
patt := defaultPattern
if len(parts) == 2 {
patt = parts[1]
}

// Name or pattern can't be empty.
if name == "" || patt == "" {
return nil, fmt.Errorf("missing name or pattern in %q", tpl[idxs[i]:end])
}

// Build the regexp pattern.
_, err := fmt.Fprintf(pattern, "%s(%s)", regexp.QuoteMeta(raw), patt)
if err != nil {
return nil, err
}

Check warning on line 47 in helpers/regex_maker.go

View check run for this annotation

Codecov / codecov/patch

helpers/regex_maker.go#L46-L47

Added lines #L46 - L47 were not covered by tests

}

// Add the remaining.
raw := tpl[end:]
pattern.WriteString(regexp.QuoteMeta(raw))

pattern.WriteByte('$')

// Compile full regexp.
reg, errCompile := regexp.Compile(pattern.String())
if errCompile != nil {
return nil, errCompile
}

Check warning on line 61 in helpers/regex_maker.go

View check run for this annotation

Codecov / codecov/patch

helpers/regex_maker.go#L60-L61

Added lines #L60 - L61 were not covered by tests

// Check for capturing groups which used to work in older versions
if reg.NumSubexp() != len(idxs)/2 {
return nil, fmt.Errorf("route %s contains capture groups in its regexp. Only non-capturing groups are accepted: e.g. (?:pattern) instead of (pattern)", template)
}

Check warning on line 66 in helpers/regex_maker.go

View check run for this annotation

Codecov / codecov/patch

helpers/regex_maker.go#L65-L66

Added lines #L65 - L66 were not covered by tests

// Done!
return reg, nil
}

func BraceIndices(s string) ([]int, error) {
Comment thread
Rishabh-Daga marked this conversation as resolved.
var level, idx int
var idxs []int
for i := 0; i < len(s); i++ {
switch s[i] {
case '{':
if level++; level == 1 {
idx = i
}
case '}':
if level--; level == 0 {
idxs = append(idxs, idx, i+1)
} else if level < 0 {
return nil, fmt.Errorf("unbalanced braces in %q", s)
}
}
}
if level != 0 {
return nil, fmt.Errorf("unbalanced braces in %q", s)
}
return idxs, nil
}
141 changes: 141 additions & 0 deletions helpers/regex_maker_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
package helpers

import (
"testing"
)

func TestGetRegexForPath(t *testing.T) {
tests := []struct {
name string
tpl string
wantErr bool
wantExpr string
}{
{
name: "well-formed template with default pattern",
tpl: "/orders/{id}",
wantErr: false,
wantExpr: "^/orders/([^/]*)$",
},
{
name: "well-formed template with custom pattern",
tpl: "/orders/{id:[0-9]+}",
wantErr: false,
wantExpr: "^/orders/([0-9]+)$",
},
{
name: "missing name in template",
tpl: "/orders/{:pattern}",
wantErr: true,
},
{
name: "missing pattern in template",
tpl: "/orders/{name:}",
wantErr: true,
},
{
name: "unbalanced braces in template",
tpl: "/orders/{id",
wantErr: true,
},
{
name: "unbalanced braces in template",
tpl: "/orders/id}",
wantErr: true,
},
{
name: "template with multiple variables",
tpl: "/orders/{id:[0-9]+}/items/{itemId}",
wantErr: false,
wantExpr: "^/orders/([0-9]+)/items/([^/]*)$",
},
{
name: "OData formatted URL with single quotes",
tpl: "/entities('{id}')",
wantErr: false,
wantExpr: "^/entities\\('([^/]*)'\\)$",
},
{
name: "OData formatted URL with custom pattern",
tpl: "/entities('{id:[0-9]+}')",
wantErr: false,
wantExpr: "^/entities\\('([0-9]+)'\\)$",
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := GetRegexForPath(tt.tpl)
if (err != nil) != tt.wantErr {
t.Errorf("GetRegexForPath() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !tt.wantErr && got.String() != tt.wantExpr {
t.Errorf("GetRegexForPath() = %v, want %v", got.String(), tt.wantExpr)
}
})
}
}

func TestBraceIndices(t *testing.T) {
tests := []struct {
name string
s string
want []int
wantErr bool
}{
{
name: "well-formed braces",
s: "/orders/{id}/items/{itemId}",
want: []int{8, 12, 19, 27},
wantErr: false,
},
{
name: "unbalanced braces",
s: "/orders/{id/items/{itemId}",
wantErr: true,
},
{
name: "unbalanced braces",
s: "/orders/{id}/items/{itemId",
wantErr: true,
},
{
name: "no braces",
s: "/orders/id/items/itemId",
want: []int{},
wantErr: false,
},
{
name: "OData formatted URL with single quotes",
s: "/entities('{id}')",
want: []int{11, 15},
wantErr: false,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := BraceIndices(tt.s)
if (err != nil) != tt.wantErr {
t.Errorf("BraceIndices() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !tt.wantErr && !equal(got, tt.want) {
t.Errorf("BraceIndices() = %v, want %v", got, tt.want)
}
})
}
}

func equal(a, b []int) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}
34 changes: 25 additions & 9 deletions parameters/path_parameters.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import (
"fmt"
"net/http"
"regexp"
"strconv"
"strings"

Expand Down Expand Up @@ -54,14 +55,34 @@
if pathSegments[x] == "" { // skip empty segments
continue
}
i := strings.IndexRune(pathSegments[x], '{')
if i > -1 {

r, err := helpers.GetRegexForPath(pathSegments[x])
if err != nil {
continue

Check warning on line 61 in parameters/path_parameters.go

View check run for this annotation

Codecov / codecov/patch

parameters/path_parameters.go#L61

Added line #L61 was not covered by tests
}

re := regexp.MustCompile(r.String())
matches := re.FindStringSubmatch(submittedSegments[x])
matches = matches[1:]

// Check if it is well-formed.
idxs, errBraces := helpers.BraceIndices(pathSegments[x])
if errBraces != nil {
continue

Check warning on line 71 in parameters/path_parameters.go

View check run for this annotation

Codecov / codecov/patch

parameters/path_parameters.go#L71

Added line #L71 was not covered by tests
}

idx := 0

for _, match := range matches {

isMatrix := false
isLabel := false
// isExplode := false
isSimple := true
paramTemplate := pathSegments[x][i+1 : len(pathSegments[x])-1]
paramTemplate := pathSegments[x][idxs[idx]+1 : idxs[idx+1]-1]
idx += 2 // move to the next brace pair
paramName := paramTemplate

// check for an asterisk on the end of the parameter (explode)
if strings.HasSuffix(paramTemplate, helpers.Asterisk) {
// isExplode = true
Expand All @@ -83,12 +104,7 @@
continue
}

paramValue := ""

// extract the parameter value from the path.
if x < len(submittedSegments) {
paramValue = submittedSegments[x]
}
paramValue := match

if paramValue == "" {
// Mandatory path parameter cannot be empty
Expand Down
Loading
Loading