Skip to content

Commit

Permalink
Add wildcard nodes #59
Browse files Browse the repository at this point in the history
  • Loading branch information
Marcel Ludwig committed Oct 26, 2020
1 parent e03ec82 commit c934719
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 8 deletions.
4 changes: 1 addition & 3 deletions server/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,9 +74,7 @@ func New(cmdCtx context.Context, log logrus.FieldLogger, conf *runtime.HTTPConfi
mux = NewMux(v.Mux.APIPath, v.Mux.FS[0].GetHandler(), v.Mux.SPA[0].GetHandler())
for _, endpoint := range v.Mux.API {
h := endpoint.GetHandler()
path := endpoint.GetMatcher().String()
// TODO: wildcard
mux.MustAddRoute(path[1:len(path)-1], h)
mux.MustAddRoute(endpoint.Name(), h)
}
break
}
Expand Down
30 changes: 25 additions & 5 deletions server/mux.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package server

import (
"context"
"fmt"
"net/http"
"strings"

Expand Down Expand Up @@ -44,17 +45,29 @@ var allowedMethods = []string{
}

func (m *Mux) MustAddRoute(path string, handler http.Handler) *Mux {
const wildcardReplacement = "/{_couper_wildcardMatch*}"
const wildcardSearch = "/**"

// TODO: handle method option per endpoint
// TODO: ensure uppercase method string if passed as argument
for _, method := range allowedMethods {
m.root.MustAdd(method+" "+path, &openapi3filter.Route{
pathOptions := &pathpattern.Options{}

if strings.HasSuffix(path, "/**") {
pathOptions.SupportRegExp = true
path = path[:len(path)-len(wildcardSearch)] + wildcardReplacement
}

node, err := m.root.CreateNode(method+" "+path, pathOptions)
if err != nil {
panic(fmt.Errorf("create path node failed: %s %q: %v", method, path, err))
}

node.Value = &openapi3filter.Route{
Method: method,
Path: path,
Handler: handler,
}, &pathpattern.Options{
SupportRegExp: false,
SupportWildcard: false,
})
}
}
return m
}
Expand Down Expand Up @@ -105,6 +118,13 @@ func (m *Mux) FindHandler(req *http.Request) http.Handler {
}

ctx := req.Context()

const wcm = "_couper_wildcardMatch"
if wildcardMatch, ok := pathParams[wcm]; ok {
ctx = context.WithValue(ctx, request.Wildcard, wildcardMatch)
delete(pathParams, wcm)
}

ctx = context.WithValue(ctx, request.PathParams, pathParams)
*req = *req.Clone(ctx)

Expand Down

0 comments on commit c934719

Please sign in to comment.