gorilla – Stop matching after first match in go/mux-ThrowExceptions

Exception or error:

I have the following router:

func testHttp() {

    r := mux.NewRouter()
    s := r.PathPrefix("/cmd").Subrouter()
    s.HandleFunc("/{cmd}", cmd)
    http.Handle("/", r)

    http.ListenAndServe(":8090", nil)

When I make a request such as localhost:8090/cmd/ls -la then the cmd handler is executed correctly. However If I pass in something like localhost:8090/cmd/ls -la /home/foo I get a 404. This implies that gorilla/mux keeps matching if it detects a /. So how do I configure it such that everything after a particular matched path (in this case /cmd/) is considered a parameter to the path? Presumably I could just resort to using GET parameters but can this be achieved if using the /rest-endpoint/params-containing/ as well ?

How to solve:

/ is a directory separator for URLs, so what mux is doing is correct that it is separating and matching segments delimited by /. If you want to pass ls -la /home/foo as a path parameter, then you should escape the / characters, and write %2F. Then mux will run correctly.

Another option can be to install a handler to PathPrefix /cmd/. Then you have to parse the remaining part of the path in your handler, but you can treat ‘/’ the way you want.

Leave a Reply

Your email address will not be published. Required fields are marked *