diff --git a/go.mod b/go.mod index 76920db..0e859a6 100644 --- a/go.mod +++ b/go.mod @@ -1,5 +1,7 @@ module github.com/mitchell/lambdarouter +go 1.14 + require ( github.com/aws/aws-lambda-go v1.10.0 github.com/davecgh/go-spew v1.1.1 // indirect diff --git a/router.go b/router.go index 1df71f4..3fa2b40 100644 --- a/router.go +++ b/router.go @@ -5,6 +5,7 @@ import ( "encoding/json" "fmt" "net/http" + "regexp" "strings" "github.com/aws/aws-lambda-go/events" @@ -81,9 +82,10 @@ func (r Router) Invoke(ctx context.Context, payload []byte) ([]byte, error) { path := req.Path for param, value := range req.PathParameters { - oldValue := fmt.Sprintf("/%s/", value) - newValue := fmt.Sprintf("/{%s}/", param) - path = strings.Replace(path, oldValue, newValue, -1) + r := regexp.MustCompile(fmt.Sprintf("/(%s)(/|$)", value)) + path = r.ReplaceAllStringFunc(path, func(m string) string { + return strings.Replace(m, value, fmt.Sprintf("{%s}", param), -1) + }) } i, found := r.events.Get([]byte(req.HTTPMethod + path)) diff --git a/router_test.go b/router_test.go index 7896967..04c3481 100644 --- a/router_test.go +++ b/router_test.go @@ -51,6 +51,7 @@ func TestRouter(t *testing.T) { desc(t, 4, "insert routes with the specified prefix succesfully") r.Group("/ding", func(r *Router) { r.Post("dong/{door}", handler) + r.Post("{dong}/door", handler) }) } @@ -89,6 +90,20 @@ func TestRouter(t *testing.T) { _, err = r.Invoke(ctx, nil) a.Error(err) + + e = events.APIGatewayProxyRequest{ + Path: "/prefix/ding/talal/door", + HTTPMethod: http.MethodPost, + PathParameters: map[string]string{"dong": "talal"}, + } + + desc(t, 4, "should succesfully route and invoke a defined route") + ejson, _ = json.Marshal(e) + + res, err = r.Invoke(ctx, ejson) + + a.NoError(err) + a.Exactly("null", string(res)) } }