Skip to content

Commit

Permalink
re-implement ^%s$ in dynamic routes the-benchmarker/web-frameworks#11…
Browse files Browse the repository at this point in the history
  • Loading branch information
nbari committed Mar 31, 2019
1 parent 9b54dc8 commit 971f372
Show file tree
Hide file tree
Showing 5 changed files with 42 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .circleci/config.yml
Expand Up @@ -5,6 +5,7 @@ workflows:
jobs:
- test-latest
- test-1.11
- test-1.12
- test-1.10
- test-1.9
- test-1.8
Expand All @@ -17,6 +18,10 @@ jobs:
steps:
- checkout
- run: make test
test-1.12:
<<: *test-template
docker:
- image: circleci/golang:1.12
test-1.11:
<<: *test-template
docker:
Expand Down
1 change: 1 addition & 0 deletions .travis.yml
Expand Up @@ -9,6 +9,7 @@ go:
- "1.9"
- "1.10"
- "1.11"
- "1.12"
- master

before_install:
Expand Down
6 changes: 6 additions & 0 deletions dynamic.go
Expand Up @@ -2,6 +2,7 @@ package violetear

import (
"errors"
"fmt"
"regexp"
"strings"
)
Expand All @@ -13,6 +14,11 @@ func (d dynamicSet) Set(name, regex string) error {
return errors.New("dynamic route name must start with a colon ':'")
}

// fix regex
if !strings.HasPrefix(regex, "^") {
regex = fmt.Sprintf("^%s$", regex)
}

r := regexp.MustCompile(regex)
d[name] = r

Expand Down
2 changes: 1 addition & 1 deletion dynamic_test.go
Expand Up @@ -38,5 +38,5 @@ func TestFixRegex(t *testing.T) {
s := make(dynamicSet)
s.Set(":name", "az")
rx := s[":name"]
expect(t, rx.String(), "az")
expect(t, rx.String(), "^az$")
}
29 changes: 29 additions & 0 deletions violetear_test.go
Expand Up @@ -60,6 +60,7 @@ type testDynamicRoutes struct {
var dynamicRoutes = []testDynamicRoutes{
{":uuid", `^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`},
{":ip", `^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$`},
{":id", `\d+`},
}

var routes = []testRouter{
Expand Down Expand Up @@ -461,6 +462,34 @@ func TestContextNamedParams(t *testing.T) {
expect(t, w.Code, 200)
}

func TestContextNamedParamsFixRegex(t *testing.T) {
router := New()

for _, v := range dynamicRoutes {
router.AddRegex(v.name, v.regex)
}

handler := func(w http.ResponseWriter, r *http.Request) {
params := r.Context().Value(ParamsKey).(Params)
if r.Method == "GET" {
expect(t, params[":id"], "123")
}
w.Write([]byte("fix regex ^...$"))
}

router.HandleFunc("/test/:id", handler, "GET")

w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/test/foo123bar", nil)
router.ServeHTTP(w, req)
expect(t, w.Code, 404)

w = httptest.NewRecorder()
req, _ = http.NewRequest("GET", "/test/123", nil)
router.ServeHTTP(w, req)
expect(t, w.Code, 200)
}

type contextKey string

func (c contextKey) String() string {
Expand Down

0 comments on commit 971f372

Please sign in to comment.