Search code examples
web-applicationsgoroutermuxgorilla

Go Gorilla mux to handles API requests


I want to get the map structure from the following Gorilla Mux router input.package main

For example,

 router.Methods("GET").Path("/api/{action}").HandlerFunc(httpLog(myHandler))

func myHandler(rw http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
    log.Println(vars["action"])
}

Serves 0.0.0.0:3000/api/input and this prints out the string input

What if I want to be able to receive requests like:

0.0.0.0:3000/api/v3?id=hello&password=great&product=ipad&confirm=true

And from this requests, I want to get a map of:

map["id"] = "hello"
map["password"] = "great"
map["product"] = "ipad"
map["confirm"] = "true"

Solution

  • Will you want me to do?

    func myHandler(r http.ResponseWriter, q *http.Request) {
        vars := mux.Vars(q)
        fmt.Println(vars["action"])
    
        fmt.Println(q.FormValue("id"))
        fmt.Println(q.FormValue("password"))
        fmt.Println(q.FormValue("product")) 
        fmt.Println(q.FormValue("confirm"))     
    }