[ch33079] Handled trailing parameters

This commit is contained in:
Talal 2020-08-11 10:47:17 +02:00
parent ccb3bfa385
commit d42e97e574
3 changed files with 22 additions and 3 deletions

2
go.mod
View File

@ -1,5 +1,7 @@
module github.com/mitchell/lambdarouter module github.com/mitchell/lambdarouter
go 1.14
require ( require (
github.com/aws/aws-lambda-go v1.10.0 github.com/aws/aws-lambda-go v1.10.0
github.com/davecgh/go-spew v1.1.1 // indirect github.com/davecgh/go-spew v1.1.1 // indirect

View File

@ -5,6 +5,7 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"net/http" "net/http"
"regexp"
"strings" "strings"
"github.com/aws/aws-lambda-go/events" "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 path := req.Path
for param, value := range req.PathParameters { for param, value := range req.PathParameters {
oldValue := fmt.Sprintf("/%s/", value) r := regexp.MustCompile(fmt.Sprintf("/(%s)(/|$)", value))
newValue := fmt.Sprintf("/{%s}/", param) path = r.ReplaceAllStringFunc(path, func(m string) string {
path = strings.Replace(path, oldValue, newValue, -1) return strings.Replace(m, value, fmt.Sprintf("{%s}", param), -1)
})
} }
i, found := r.events.Get([]byte(req.HTTPMethod + path)) i, found := r.events.Get([]byte(req.HTTPMethod + path))

View File

@ -51,6 +51,7 @@ func TestRouter(t *testing.T) {
desc(t, 4, "insert routes with the specified prefix succesfully") desc(t, 4, "insert routes with the specified prefix succesfully")
r.Group("/ding", func(r *Router) { r.Group("/ding", func(r *Router) {
r.Post("dong/{door}", handler) r.Post("dong/{door}", handler)
r.Post("{dong}/door", handler)
}) })
} }
@ -89,6 +90,20 @@ func TestRouter(t *testing.T) {
_, err = r.Invoke(ctx, nil) _, err = r.Invoke(ctx, nil)
a.Error(err) 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))
} }
} }