httpgoresthttp-parameters

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.


Solution

  • If you are using Go 1.22, you can easily retrieve the path parameters with r.PathValue(). For example:

    package main
    
    import (
        "fmt"
        "net/http"
        "net/http/httptest"
    )
    
    func main() {
        mux := http.NewServeMux()
        mux.HandleFunc("/provisions/{id}", func(w http.ResponseWriter, r *http.Request) {
            fmt.Println("Provision ID: ", r.PathValue("id"))
        })
    
        mux.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/provisions/123", nil))
        mux.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/provisions/456", nil))
    }
    

    Demo in Go Playground. Source: https://pkg.go.dev/net/http#Request.PathValue