Go to: Get path parameters from http.Request

I am developing a REST API with Go, but I do not know how I can map paths and extract path parameters from them.

I need 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 only the package httpinstead of web frameworks, if possible.

Thanks.

+4
source share
1 answer

If you do not want to use any of the many available routing packages, you need to analyze the path yourself:

Pave the / provision path to your handler

http.HandleFunc("/provisions/", Provisions)

Then split the path as needed in the handler

id := strings.TrimPrefix(req.URL.Path, "/provisions/")
// or use strings.Split, or use regexp, etc.
+8
source

Source: https://habr.com/ru/post/1620361/


All Articles