Reputation: 97
I'm trying to find a way to create special routes to that would allow post request to work with a params ( /url/:param ).
I've tried something like this :
http.HandleFunc("/myroute/:myparam",myfunction)
And i was hopping to be able to get the params as of the http-request in side "myfunction" with req.Form
but it keeps on failing on me and i get 404'ed.
I recognize it is something strange to ask as i could pass my params in the body of the function, but for ease of use/display i've been asked to be able to pregenerate a list of static "routes" on some preset so that it can be distributed as different urls + optional params instead of one url for everybody + params..
Upvotes: 0
Views: 3638
Reputation: 640
You can define a handle function on /
and then have custom parsing of the path, like splitting on /
character.
http.HandleFunc("/", dispatcher)
In this way, your handler will accept everything and you can route the requests manually to the respective function. For example, PUT calls would expect some parameter after the resource (/orders/2
)
logs.Info("The URL that you are calling is: " + req.URL.Path)
Output: The URL that you are calling is: /orders/2
You can also do:
http.HandleFunc("/orders/", dispatcher)
to narrow down the scope of your handler. In this way, you can leave the validation of the resource portion of the path to Go http package.
Upvotes: 1
Reputation: 2087
It's not possible with the default Mux
, but you can use alternative routers like httprouter, Gorilla Mux or chi.
Here is an example of httprouter
usage:
package main
import (
"fmt"
"github.com/julienschmidt/httprouter"
"net/http"
)
func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name"))
}
func main() {
router := httprouter.New()
router.GET("/hello/:name", Hello)
http.ListenAndServe(":8080", router)
}
Upvotes: 6