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

feat: make redirects work for wildcard routes #21

Merged
merged 1 commit into from
Oct 19, 2021
Merged
Show file tree
Hide file tree
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
1 change: 0 additions & 1 deletion example/file-server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ func main() {
)

router.GET("/", indexHandler)
router.GET("/files/", bunrouter.HTTPHandler(fileServer))
router.GET("/files/*path", bunrouter.HTTPHandler(fileServer))

log.Println("listening on http://localhost:9999")
Expand Down
9 changes: 1 addition & 8 deletions group.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,14 +110,7 @@ func (g *Group) Handle(meth string, path string, handler HandlerFunc) {
handler = g.handlerWithMiddlewares(handler)
}

var slash bool

if len(path) > 1 && path[len(path)-1] == '/' {
slash = true
path = path[:len(path)-1]
}

node := g.router.tree.addRoute(path)
node, slash := g.router.tree.addRoute(path)
node.setHandler(meth, routeHandler{fn: handler, slash: slash})
}

Expand Down
154 changes: 99 additions & 55 deletions node.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ type node struct {
params map[string]int // param name => param position
handlerMap *handlerMap

parent *node
wildcard *node
colon *node
parent *node
colon *node
isWildcard bool

nodes []*node
index struct {
Expand All @@ -26,12 +26,12 @@ type node struct {
}
}

func (n *node) addRoute(route string) *node {
func (n *node) addRoute(route string) (*node, bool) {
if route == "/" {
return n
return n, false
}

parts, params := splitRoute(route[1:])
parts, params, slash := splitRoute(route)
currNode := n

for _, part := range parts {
Expand All @@ -42,15 +42,13 @@ func (n *node) addRoute(route string) *node {
currNode.params = params
n.indexNodes()

return currNode
return currNode, slash
}

func (n *node) addPart(part string) *node {
if part == "*" {
if n.wildcard == nil {
n.wildcard = &node{part: "*"}
}
return n.wildcard
n.isWildcard = true
return n
}

if part == ":" {
Expand Down Expand Up @@ -132,9 +130,9 @@ func (n *node) findRoute(meth, path string) (*node, routeHandler, int) {
} else {
partLen := len(childNode.part)
if strings.HasPrefix(path, childNode.part) {
node, handler, wildcard := childNode.findRoute(meth, path[partLen:])
node, handler, wildcardLen := childNode.findRoute(meth, path[partLen:])
if handler.fn != nil {
return node, handler, wildcard
return node, handler, wildcardLen
}
if node != nil {
found = node
Expand All @@ -160,12 +158,15 @@ func (n *node) findRoute(meth, path string) (*node, routeHandler, int) {
}
}

if n.wildcard != nil {
if handler := n.wildcard.handler(meth); handler.fn != nil {
return n.wildcard, handler, pathLen
if n.isWildcard {
if handler := n.handler(meth); handler.fn != nil {
if handler.slash {
pathLen--
}
return n, handler, pathLen
}
if found == nil {
return n.wildcard, routeHandler{}, 0
return n, routeHandler{}, 0
}
}

Expand Down Expand Up @@ -204,11 +205,6 @@ func (n *node) indexNodes() {
n.colon.parent = n
n.colon.indexNodes()
}

if n.wildcard != nil {
n.wildcard.parent = n
n.wildcard.indexNodes()
}
}

func (n *node) setHandler(verb string, handler routeHandler) {
Expand All @@ -230,55 +226,103 @@ func (n *node) handler(verb string) routeHandler {

//------------------------------------------------------------------------------

func splitRoute(route string) ([]string, map[string]int) {
var parts []string
var params []string
type routeParser struct {
segments []string
i int

acc []string
parts []string
}

func (p *routeParser) valid() bool {
return p.i < len(p.segments)
}

func (p *routeParser) next() string {
s := p.segments[p.i]
p.i++
return s
}

func (p *routeParser) accumulate(s string) {
p.acc = append(p.acc, s)
}

func (p *routeParser) finalizePart(withSlash bool) {
if part := join(p.acc, withSlash); part != "" {
p.parts = append(p.parts, part)
p.acc = p.acc[:0]
}
if p.valid() {
p.acc = append(p.acc, "")
}
}

func join(ss []string, withSlash bool) string {
s := strings.Join(ss, "/")
if s == "" {
return s
}
if withSlash {
return s + "/"
}
return s
}

func splitRoute(route string) (_ []string, _ map[string]int, slash bool) {
if route == "" || route[0] != '/' {
panic(fmt.Errorf("invalid route: %q", route))
}

if route == "/" {
return []string{}, nil, false
}
route = route[1:] // trim "/"

if strings.HasSuffix(route, "/") {
slash = true
route = route[:len(route)-1]
}

ss := strings.Split(route, "/")
if len(ss) == 0 {
panic(fmt.Errorf("invalid route: %q", route))
}

var acc []string
for i, part := range ss {
if part == "" {
acc = append(acc, "")
continue
}
p := routeParser{
segments: ss,
}
var params []string

switch firstChar := part[0]; firstChar {
case ':', '*':
if firstChar == '*' && i != len(ss)-1 {
panic(fmt.Errorf("wildcard must be in the end of the route: %q", route))
}
for p.valid() {
segment := p.next()

if len(acc) > 0 {
parts = append(parts, strings.Join(acc, "/")+"/")
acc = acc[:0]
}
if i != len(ss)-1 {
acc = append(acc, "")
}
if segment == "" {
p.accumulate("")
continue
}

parts = append(parts, string(firstChar))
params = append(params, part[1:])
switch firstChar := segment[0]; firstChar {
case ':':
p.finalizePart(true)
p.parts = append(p.parts, string(firstChar))
params = append(params, segment[1:])
case '*':
p.finalizePart(false)
slash = len(p.parts) > 0
p.parts = append(p.parts, string(firstChar))
params = append(params, segment[1:])
default:
acc = append(acc, part)
p.accumulate(segment)
}
}

if len(acc) > 0 {
part := strings.Join(acc, "/")
if part == "" {
part = "/"
}
parts = append(parts, part)
}
p.finalizePart(false)

if len(params) > 0 {
return parts, paramMap(route, params)
return p.parts, paramMap(route, params), slash
}
return parts, nil
return p.parts, nil, slash
}

func paramMap(route string, params []string) map[string]int {
Expand Down
2 changes: 1 addition & 1 deletion request.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ func (ps *Params) findParam(paramIndex int) (string, bool) {
currParamIndex := len(ps.node.params) - 1

// Wildcard can be only in the final node.
if ps.node.part[0] == '*' {
if ps.node.isWildcard {
pathLen -= int(ps.wildcardLen)
if currParamIndex == paramIndex {
return path[pathLen:], true
Expand Down
4 changes: 2 additions & 2 deletions router.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ func (r *Router) lookup(w http.ResponseWriter, req *http.Request) (HandlerFunc,
return r.notFoundHandler, Params{}
}

trailingSlash := path[len(path)-1] == '/' && len(path) > 1
trailingSlash := len(path) > 1 && path[len(path)-1] == '/'
if trailingSlash {
path = path[:len(path)-1]
unescapedPath = unescapedPath[:len(unescapedPath)-1]
Expand All @@ -77,7 +77,7 @@ func (r *Router) lookup(w http.ResponseWriter, req *http.Request) (HandlerFunc,
return r.methodNotAllowedHandler, Params{}
}

if trailingSlash != handler.slash {
if wildcardLen == 0 && trailingSlash != handler.slash {
if handler.slash {
// Need to add a slash.
return redirectHandler(unescapedPath + "/"), Params{}
Expand Down
Loading