Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] Add routeType attribute & logic to attempt static routes before parameterized routes #6

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 16 additions & 4 deletions lmdrouter.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ type route struct {
re *regexp.Regexp
paramNames []string
methods map[string]resource
routeType string
}

type resource struct {
Expand Down Expand Up @@ -178,7 +179,8 @@ func (l *Router) Route(method, path string, handler Handler, middleware ...Middl
r, ok := l.routes[path]
if !ok {
r = route{
methods: make(map[string]resource),
methods: make(map[string]resource),
routeType: "static", // assume static until we encounter a parameter
}

// create a regular expression from the path
Expand All @@ -193,6 +195,7 @@ func (l *Router) Route(method, path string, handler Handler, middleware ...Middl
if strings.HasPrefix(part, ":") {
r.paramNames = append(r.paramNames, strings.TrimPrefix(part, ":"))
re = fmt.Sprintf("%s/([^/]+)", re)
r.routeType = "dynamic"
} else {
re = fmt.Sprintf("%s/%s", re, part)
}
Expand Down Expand Up @@ -245,9 +248,14 @@ func (l *Router) Handler(
ctx context.Context,
req events.APIGatewayProxyRequest,
) (events.APIGatewayProxyResponse, error) {
rsrc, err := l.matchRequest(&req)
// match static routes first
rsrc, err := l.matchRequest(&req, "static")
if err != nil {
return HandleError(err)
// match dynamic routes if no resource
rsrc, err = l.matchRequest(&req, "dynamic")
if err != nil {
return HandleError(err)
}
}

handler := rsrc.handler
Expand All @@ -262,7 +270,7 @@ func (l *Router) Handler(
return handler(ctx, req)
}

func (l *Router) matchRequest(req *events.APIGatewayProxyRequest) (
func (l *Router) matchRequest(req *events.APIGatewayProxyRequest, routeType string) (
rsrc resource,
err error,
) {
Expand All @@ -276,6 +284,10 @@ func (l *Router) matchRequest(req *events.APIGatewayProxyRequest) (

// find a route that matches the request
for _, r := range l.routes {
if r.routeType != routeType {
continue
}

// does the path match?
matches := r.re.FindStringSubmatch(req.Path)
if matches == nil {
Expand Down