I'm developing a REST API with Go, but I don't know how can I do the path mappings and retrieve the path parameters from them.
I want something like this:
func main() {
http.HandleFunc("/provisions/:id", Provisions) //<-- How can I map "id" parameter in the path?
http.ListenAndServe(":8080", nil)
}
func Provisions(w http.ResponseWriter, r *http.Request) {
//I want to retrieve here "id" parameter from request
}
I would like to use just http
package instead of web frameworks, if it is possible.
Thanks.
You can use golang gorilla/mux package's router to do the path mappings and retrieve the path parameters from them.
In Golang, the standard package net/http has a routing function. That feature is called multiplexer in Golang. However, the standard package does not support path parameters, so if you want to use it, you need to prepare an external package or extend the standard multiplexer.
To use the url we need to import the o package called net/url. We can pass the url as the argument to the functions of the url. For example, if we have an url and we want to check the port of the given url by calling the function of the url like Port() where u =url. Parse(“www.xyz.com”).
Path parameters are variable parts of a URL path. They are typically used to point to a specific resource within a collection, such as a user identified by ID. A URL can have several path parameters, each denoted with curly braces { } . GET /users/{id}
If you don't want to use any of the multitude of the available routing packages, then you need to parse the path yourself:
Route the /provisions path to your handler
http.HandleFunc("/provisions/", Provisions)
Then split up the path as needed in the handler
id := strings.TrimPrefix(req.URL.Path, "/provisions/") // or use strings.Split, or use regexp, etc.
You can use golang gorilla/mux package's router to do the path mappings and retrieve the path parameters from them.
import ( "fmt" "github.com/gorilla/mux" "net/http" ) func main() { r := mux.NewRouter() r.HandleFunc("/provisions/{id}", Provisions) http.ListenAndServe(":8080", r) } func Provisions(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) id, ok := vars["id"] if !ok { fmt.Println("id is missing in parameters") } fmt.Println(`id := `, id) //call http://localhost:8080/provisions/someId in your browser //Output : id := someId }
I used standard gin routing and handling request parameters from context parameters.
Use this in registering your endpoint:
func main() {
r := gin.Default()
g := r.Group("/api")
{
g.GET("/template/get/:Id", templates.TemplateGetIdHandler)
}
r.Run()
}
And use this function in handler
func TemplateGetIdHandler(c *gin.Context) {
req := getParam(c, "Id")
//your stuff
}
func getParam(c *gin.Context, paramName string) string {
return c.Params.ByName(paramName)
}
Use this in registering your endpoint:
func main() {
r := gin.Default()
g := r.Group("/api")
{
g.GET("/template/get", templates.TemplateGetIdHandler)
}
r.Run()
}
And use this function in handler
type TemplateRequest struct {
Id string `form:"id"`
}
func TemplateGetIdHandler(c *gin.Context) {
var request TemplateRequest
err := c.Bind(&request)
if err != nil {
log.Println(err.Error())
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
}
//your stuff
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With