Skip to content
Permalink
Browse files

re-implement ^%s$ in dynamic routes the-benchmarker/web-frameworks#11…

  • Loading branch information...
nbari committed Mar 31, 2019
1 parent 9b54dc8 commit 971f3729520176a408b28de36d6f283f13b8e6d3
Showing with 42 additions and 1 deletion.
  1. +5 −0 .circleci/config.yml
  2. +1 −0 .travis.yml
  3. +6 −0 dynamic.go
  4. +1 −1 dynamic_test.go
  5. +29 −0 violetear_test.go
@@ -5,6 +5,7 @@ workflows:
jobs:
- test-latest
- test-1.11
- test-1.12
- test-1.10
- test-1.9
- test-1.8
@@ -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:
@@ -9,6 +9,7 @@ go:
- "1.9"
- "1.10"
- "1.11"
- "1.12"
- master

before_install:
@@ -2,6 +2,7 @@ package violetear

import (
"errors"
"fmt"
"regexp"
"strings"
)
@@ -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

@@ -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$")
}
@@ -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{
@@ -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 {

0 comments on commit 971f372

Please sign in to comment.
You can’t perform that action at this time.