bmizerany / pat

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Broken redirects with trailing slashes in patterns

paulhammond opened this issue · comments

If there is a trailing slash in a pattern then redirects don't work as expected. Take the example server from the documentation, but add a slash to the pattern:

package main

import (
    "io"
    "net/http"
    "github.com/bmizerany/pat"
    "log"
)

// hello world, the web server
func HelloServer(w http.ResponseWriter, req *http.Request) {
    io.WriteString(w, "hello, "+req.URL.Query().Get(":name")+"!\n")
}

func main() {
    m := pat.New()
    m.Get("/hello/:name/", http.HandlerFunc(HelloServer))

    http.Handle("/", m)
    err := http.ListenAndServe(":12345", nil)
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}

If we request /hello/bob/ everything works as expected:

$ curl http://localhost:12345/hello/bob/
hello, bob!

But if we request a url without a trailing slash like /hello/bob we get a broken redirect to /hello/:name/

$ curl -si http://localhost:12345/hello/bob | grep Location
Location: /hello/:name/

It looks like the code is using the pattern as the redirect target, instead of the requested url.

The docs on this are also unclear, they say "A pattern ending with a slash will get an implicit redirect to it's non-slash version." - but the redirect appears to be from the non-slash version.

Hmmm, I attempted to add my code change to this issue, but it ended up creating a new issue (#22).