Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go: Get path parameters from http.Request

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.

like image 768
Héctor Avatar asked Dec 16 '15 14:12

Héctor


People also ask

How do I get the PATH variable in Golang?

You can use golang gorilla/mux package's router to do the path mappings and retrieve the path parameters from them.

What are routes in Golang?

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.

How do I get Golang URL?

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”).

What is path parameter in URL?

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}


3 Answers

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. 
like image 105
JimB Avatar answered Sep 18 '22 11:09

JimB


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 } 
like image 24
nipuna Avatar answered Sep 19 '22 11:09

nipuna


Golang read value from URL query "/template/get/123".

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)
}

Golang read value from URL query "/template/get?id=123".

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
}
like image 24
Leonid Pavlov Avatar answered Sep 22 '22 11:09

Leonid Pavlov