Passing a URL as URL param

885 views Asked by At

I have this route that was written with route params

/properties/configurations/:name/:value

and when I call with with a URL as value like that

/properties/configurations/app.url/http://test.test

it doesn't hit my Revel controller I guess because the slash confuses it. I tried when calling the Javascript request with encodeURIComponent() so it removes the slashes and other chars that are problematic but it still doesn't hit the controller and gives 404.

The problem is it is used in a public API and I cannot change it to pass this data in the body instead so I'm trying to figure out how can I make revel recognize the pattern and correctly put the values inside {name} and {value}

2

There are 2 answers

0
Zombo On

You just need to use one of the escape functions:

package main
import "net/url"

func main() {
   s := "http://test.test"
   {
      t := url.PathEscape(s)
      println(t == "http:%2F%2Ftest.test")
   }
   {
      t := url.QueryEscape(s)
      println(t == "http%3A%2F%2Ftest.test")
   }
}
0
JJM On

If you're able to pass the URL encoded URL to your Golang server as a path variable, you can run it through url.PathUnescape(str).

If the problem is that your router isn't reaching the correct handlers because the characters in your path variable aren't matching correctly, it's possible that you've incorrectly defined that path matcher. I don't have experience with revel, but with mux (github.com/gorilla/mux) I would expect it to look like the following:

package main

import (
    "net/http"
    "net/url"
    "github.com/gorilla/mux"
)

func main() {

    r := mux.NewRouter()
    r.HandleFunc("/properties/configurations/app.url/{nestedURL:.*}", myHandler)
 
    http.ListenAndServe(":8080", r)

}

func myHandler(w http.ResponseWriter, r *http.Request){
    nestedURL := mux.Vars(r)["nestedURL"]
    unescapedPath, err := url.PathUnescape(nestedURL)
    if err != nil {
        // handle err
    }
}

The above example might even work without requiring you to URL encode the nested URL (but I really do suggest you URL encode it).