如何使用“ slashUrls”代替QueryString。 (不订购)

I'm using gorilla-mux to route my urls but I found a difficulty:

My client prefer a url with slashes instead of a traditional query string. I mean:

domain/handler/filter1/val1/filter2/val2...

Instead of

domain/handler?filter1=val1&filter2=val2...

Important Issues: When using query string, the 'variables' order isn't important and any of them can be missing without get a wrong routing or a NotFound.

When using query string, the order of 'vars' isn't important and I can miss any of them without get a wrong routing At this moment I'm writting a permutation algorithm that create urls for handle them with same function.

Is there a better way to do that?

I wrote a "url generator" for my needs

https://github.com/daniloanp/SlashedQueryUrls

It's very simple and naive but it's working for me.

A good example of usage is in my reposiry:

package main

import (
    "fmt"
    "github.com/daniloanp/muxUrlGen"
    "github.com/gorilla/mux"
    "net/http"
)

func HandleUrlsWithFunc(rtr *mux.Router, urls []string, handler func(w http.ResponseWriter, r *http.Request)) {
    for _, url := range urls {
        rtr.HandleFunc(url, handler)
    }
}

func echoVars(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    fmt.Fprintln(w, r.URL.String(), "

")
    for k, i := range mux.Vars(r) {
        fmt.Fprintln(w, k, ": ", i)
    }
}

func main() {
    var url string
    var urls []string

    rtr := mux.NewRouter()

    url = "/handl/v1/{v}/v2/{v'}"
    rtr.HandleFunc(url, echoVars)
    // The above code works by we cannot missing any var OR Even

    // Using "long notation"
    urls = muxUrlGen.GetUrlVarsPermutations("/handlLong/v1/{v:[0-9]+}/v2/{v'}", true)
    HandleUrlsWithFunc(rtr, urls, echoVars)

    // Using "long notation" and Optional vars
    urls = muxUrlGen.GetUrlVarsPermutations("/handlLongOptional/v1/{v}?/v2/{v'}?", true)
    HandleUrlsWithFunc(rtr, urls, echoVars)

    // Using "short notation"
    urls = muxUrlGen.GetUrlVarsPermutations("/handlShort/{v1}/{v2}", false)
    HandleUrlsWithFunc(rtr, urls, echoVars)

    // Using "short notation" and Optional vars
    urls = muxUrlGen.GetUrlVarsPermutations("/handlShortOptional/{v1}?/{v2}?", false)
    HandleUrlsWithFunc(rtr, urls, echoVars)

    http.Handle("/", rtr)
    fmt.Println("Server running at http://127.0.0.1:8080")

    http.ListenAndServe(":8080", nil)
}

Thanks for everyone.