6

While developing a REST api in Go, how can we use path params? meaning to say what will be the format of the URI?

http://localhost:8765/myapp/{param1}/entries/{param2}

I tried using something like this to create the route but the handler function is not getting invoked.

Please note that, i intent to use only the net/http package , not any other web framework like gorilla mux.

piet.t
  • 11,718
  • 21
  • 43
  • 52
Onkar Banerjee
  • 179
  • 1
  • 2
  • 9
  • 2
    Possible duplicate of [Go: Get path parameters from http.Request](https://stackoverflow.com/questions/34314975/go-get-path-parameters-from-http-request) – Tinwor Jul 05 '17 at 07:46

3 Answers3

2

What I tend to do is nested handlers. "/" is handled by the root handler. It pops the first part of the path, assigns the rest back to req.URL.Path (effectively acting like StripPrefix), determines which handler handles routes by that prefix (if any), then chains the appropriate handler. If that handler needs to parse an ID out of the path, it can, by the same mechansim - pop the first part of the path, parse it as necessary, then act.

This not only has no external dependencies, but it is faster than any router could ever be, because the routing is hard-coded rather than dynamic. Unless routing changes at runtime (which would be pretty unusual), there is no need for routing to be handled dynamically.

Adrian
  • 42,911
  • 6
  • 107
  • 99
1

Well this is why people use frameworks like gin-gonic because this is not easy to do this in the net/http package IIUC.

Otherwise, you would need to strings.Split(r.URL.Path, "/") and work from those elements.

hendry
  • 9,725
  • 18
  • 81
  • 139
  • Ya, i had this down with gorilla Mux. But in std lib, the net/http package couldn't allow me such flexibility. I had to do with string trimming and splitting of the url path as suggested above by you. Just wanted to confirm if there is indeed any other way to get this done with anything from the std lib. I am new to GO, pardon my ignorance. The other thing i couldn't get was to have handlers based on methods.Need to access the mothod as well from the request object it seems. – Onkar Banerjee Jul 05 '17 at 08:00
  • Don't worry. All golang Web developers have had the same thoughts. ;) – hendry Jul 05 '17 at 08:36
0

With net/http the following would trigger when calling localhost:8080/myapp/foo/entries/bar

http.HandleFunc("/myapp/", yourHandlerFunction)

Then inside yourHandlerFunction, manually parse r.URL.Path to find foo and bar.

Note that if you don't add a trailing / it won't work. The following would only trigger when calling localhost:8080/myapp:

http.HandleFunc("/myapp", yourHandlerFunction)
Stéphane Bruckert
  • 21,706
  • 14
  • 92
  • 130