URL variables with net/http

158 views
Skip to first unread message

Dejan Duh

unread,
Oct 19, 2023, 7:27:59 AM10/19/23
to golang-nuts
Hi everyone. I'm building an api with net/http and I'm having trouble with url variables. How can I get the url variables form the url in the REST way. Example, if I have a url like "http:/localhost:3000/users/:id". I want to get the user with the id given from the url. What is the best way to get the id using only the standart lib? Thanks

j2gg0s

unread,
Oct 19, 2023, 9:20:32 AM10/19/23
to golang-nuts
I'm not sure what the best way is.

But I think you can refer to the existing solutions. For example gin, mux.

TheDiveO

unread,
Oct 19, 2023, 1:02:19 PM10/19/23
to golang-nuts
stdlib only with upcoming 1.22 which isn't yet released, see https://eli.thegreenplace.net/2023/better-http-server-routing-in-go-122/

gorilla mux is another 3rd party muxer with variable support https://github.com/gorilla/mux

the "best" way using only stdlib mux is to parse the path and extract the variable yourself. otherwise, wait for 1.22. or use an existing 3rd party module.

Tim Casey

unread,
Oct 19, 2023, 2:09:34 PM10/19/23
to golang-nuts


Gin does this directly.   There is nothing complicated it does.  Something like:

group := engine.Group("/service/v1")
group.GET("user/:id", handler)

And then in the handler:

id := c.Param("id")

And the rest is what ever is yours.  "engine" is a gin engine and 'c' is a gin context.

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/9b1030a6-1bc3-4b60-8e99-d98cd760beddn%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages