Browse Source

Fixed route and router to allow for multiple variables in the path.

Antonio Hernández 6 years ago
parent
commit
9b655bb052
4 changed files with 42 additions and 3 deletions
  1. 1
    0
      .gitignore
  2. 2
    2
      route.go
  3. 38
    0
      route_test.go
  4. 1
    1
      router.go

+ 1
- 0
.gitignore View File

4
 *.tmp
4
 *.tmp
5
 *.out
5
 *.out
6
 .DS_Store
6
 .DS_Store
7
+.idea

+ 2
- 2
route.go View File

51
 	for _, routePart := range routeParts {
51
 	for _, routePart := range routeParts {
52
 		if strings.HasPrefix(routePart, `{`) && strings.HasSuffix(routePart, `}`) {
52
 		if strings.HasPrefix(routePart, `{`) && strings.HasSuffix(routePart, `}`) {
53
 			routePattern += RouteWithParamsPattern
53
 			routePattern += RouteWithParamsPattern
54
-			routePart = strings.TrimPrefix(path, `{`)
55
-			routePart = strings.TrimSuffix(path, `}`)
54
+			routePart = strings.TrimPrefix(routePart, `{`)
55
+			routePart = strings.TrimSuffix(routePart, `}`)
56
 			r.varNames = append(r.varNames, routePart)
56
 			r.varNames = append(r.varNames, routePart)
57
 		} else {
57
 		} else {
58
 			routePattern += RouteOnlyPrefixPattern + routePart
58
 			routePattern += RouteOnlyPrefixPattern + routePart

+ 38
- 0
route_test.go View File

1
+package isokit
2
+
3
+import (
4
+	"context"
5
+	"reflect"
6
+	"testing"
7
+)
8
+
9
+func TestNewRoute(t *testing.T) {
10
+	handler := func(ctx context.Context) {}
11
+
12
+	testCases := map[string]struct {
13
+		path         string
14
+		expectedVars []string
15
+	}{
16
+		"Without vars": {
17
+			"/this/is/a/path",
18
+			[]string(nil),
19
+		},
20
+		"Single var": {
21
+			"/this/{firstVar}/is/a/path",
22
+			[]string{"firstVar"},
23
+		},
24
+		"Multiple vars": {
25
+			"/this/is/{firstVar}/a/{secondVar}/path",
26
+			[]string{"firstVar", "secondVar"},
27
+		},
28
+	}
29
+
30
+	for title, tc := range testCases {
31
+		t.Run(title, func(t *testing.T) {
32
+			r := NewRoute(tc.path, handler)
33
+			if !reflect.DeepEqual(r.varNames, tc.expectedVars) {
34
+				t.Errorf("wrong vars: expected %#v, got %#v", tc.expectedVars, r.varNames)
35
+			}
36
+		})
37
+	}
38
+}

+ 1
- 1
router.go View File

92
 		routeVars := make(map[string]string)
92
 		routeVars := make(map[string]string)
93
 
93
 
94
 		for i, part := range parts {
94
 		for i, part := range parts {
95
-			routeVars[matchedRoute.varNames[i]+`}`] = part
95
+			routeVars[matchedRoute.varNames[i]] = part
96
 		}
96
 		}
97
 
97
 
98
 		var ctx context.Context
98
 		var ctx context.Context