gogorillaservemux

Gorilla Mux to handle curl request


I want to use Gorilla mux to handle api requests.

Commands will be something like:

curl http://0.0.0.0:8000/api/myapiname/v1?number=10&target=google.com&message=hello

And I am serving with following handlers:

router.Methods("GET").Path("/api/myapiname/{version}").HandlerFunc(apihandler)

func apihandler(rw http.ResponseWriter, q *http.Request) {
    vars := mux.Vars(q)
    log.Println(vars["version"])
    log.Println(q.FormValue("number"))
    log.Println(q.FormValue("target"))
    log.Println(q.FormValue("message"))
}

But for the curl requests I only get the form value of number not target and message's

What is the correct way of handle api requests using Gorilla mux? Do I need sub routing?

I just want to receive any http request of form http://0.0.0.0:8000/api/myapiname/v1?number=10&target=google.com&message=hello and be able to map its key to value

THanks!


Solution

  • You may try to add Queries to your router, in that case you will have all vars in one map.

    router.Methods("GET").Path("/api/myapiname/{version}").Queries("number", "{number:[0-9]+}", "target", "{target:[^&]+}", "message", "{message:[^&]+}").HandlerFunc(apihandler)
    
    func apihandler(rw http.ResponseWriter, q *http.Request) {
        vars := mux.Vars(q)
        log.Println(vars["version"])
        log.Println(vars("number"))
        log.Println(vars("target"))
        log.Println(vars("message"))
    }