Get the current pattern that matched an http.HandleFunc

775 views
Skip to first unread message

smb....@gmail.com

unread,
Mar 25, 2015, 8:11:04 PM3/25/15
to golan...@googlegroups.com

Is there a way to get the current route that triggered an http.HandleFunc? Maybe something like this?

http.HandleFunc("/foo/", serveFoo)
func serveFoo(rw http.ResponseWriter, req *http.Request) {
    fmt.Println(http.CurrentRoute())
    // Should print "/foo/"
}

The reason I want to get the current route is because I find myself writing code like this often.

if req.URL.Path != "/some-route/" {
    http.NotFound(resp, req)
    return
}
// or
key := req.URL.Path[len("/some-other-route/"):]

It would be nice if the code was a bit more copy-pastable and DRY like this.

if req.URL.Path != http.CurrentRoute() {
    http.NotFound(resp, req)
    return
}
// or
key := req.URL.Path[http.CurrentRoute():]

This is really just a small thing, so I'd rather not bring a whole other dependency into my project (Gorilla Mux).

Quoc-Viet Nguyen

unread,
Mar 26, 2015, 9:06:23 AM3/26/15
to smb....@gmail.com, golan...@googlegroups.com
How about using http.StripPrefix() http://golang.org/pkg/net/http/#StripPrefix ?
> --
> You received this message because you are subscribed to the Google Groups
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to golang-nuts...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.



--
Quoc-Viet Nguyen

smb....@gmail.com

unread,
Mar 26, 2015, 12:36:42 PM3/26/15
to golan...@googlegroups.com, smb....@gmail.com
Uhh... Sorry, I don't get it. How so?

I tried this, but it didn't work.

http.HandleFunc("/static/", http.StripPrefix("/static/", serveStatic))

smb....@gmail.com

unread,
Mar 26, 2015, 1:15:52 PM3/26/15
to golan...@googlegroups.com, smb....@gmail.com
Oh, wait. I think I get it.
You mean like the Go blog does it. Like this.

http.Handle("/lib/godoc/", http.StripPrefix("/lib/godoc/", http.HandlerFunc(staticHandler)))

Then, inside staticHandler req.URL.Path will just be the name of my key.

Okay. I still feel a little weird about repeating myself, but this does simplify my code in my HandlerFunc. Interesting...

Quoc-Viet Nguyen

unread,
Mar 27, 2015, 8:15:51 AM3/27/15
to smb....@gmail.com, golan...@googlegroups.com
Yeah, I don't know if there is a better way than a function like this:

func handle(path string, handler http.Handler) {
http.Handle(path, http.StripPrefix(path, handler)
}

Cheers
Reply all
Reply to author
Forward
0 new messages