2017-04-26 13:30 阅读 254


I'm trying to pass a URL as a parameter in Golang, and I haven't been able to find a solution in all of the tutorials I've looked at. The problem is that I can only get the url to return minus a crucial forward slash.

My handler looks like this:

router.HandleFunc("/new/{url}", createURL)

So the request would look like:

However, the url that I results is missing a slash:


I sure it's probably got something to do with RFC3986, but is there a way to pass in the url as it is?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    drllqg2903 drllqg2903 2018-03-14 02:01

    This particular behavior in Gorilla Mux can be changed by setting SkipClean to true.

    router := mux.NewRouter()
    router.HandleFunc("/new/", index)
    router.HandleFunc("/", index)
    http.ListenAndServe(":"+port, router)

    The relevant documentation can be found here.

    点赞 评论 复制链接分享
  • doushou6480 doushou6480 2017-04-28 01:15

    After reading the other question, I understand what do you mean. Implement a kind of URL re-writer before URL goes to gorilla/mux. The function will look like:

    func Rewriter(h http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            //Simple URL rewriter. Rewrite if it's started with API path
            pathReq := r.RequestURI
            if strings.HasPrefix(pathReq, "/new/") {
                //Use url.QueryEscape for pre go1.8
                pe := url.PathEscape(strings.TrimLeft(pathReq, "/new/"))
                r.URL.Path = "/new/" + pe
                r.URL.RawQuery = ""
            h.ServeHTTP(w, r)

    Wrap gorilla router when starting the http server:

    r := mux.NewRouter()
    // ... other handler
    r.HandleFunc("/new/{original-url}", NewHandler)
    //Wrap mux.Router using Rewriter
    log.Fatal(http.ListenAndServe(":8080", Rewriter(r)))

    Then in your URL shortener handler, the original URL can be extracted using the following code:

    func NewHandler(w http.ResponseWriter, r *http.Request) {
        vars := mux.Vars(r)
        ou := vars["original-url"]
        //Use url.QueryUnascape for pre go1.8
        originalURL, err := url.PathUnescape(ou)
        //... other processing

    IMHO, implementing URL shortener service like this is not recommended, mainly due to incorrect use of HTTP verbs. Any GET request should not leave side effect in server e.g. no record creation in database, etc.

    点赞 评论 复制链接分享