path param in URL in GO without any web framework

huangapple go评论153阅读模式
英文:

path param in URL in GO without any web framework

问题

在使用Go开发REST API时,我们如何使用路径参数?也就是说,URI的格式是什么?

我尝试使用类似以下的方式创建路由,但处理函数没有被调用。

请注意,我只打算使用net/http包,而不使用像gorilla mux这样的其他Web框架。

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

英文:

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.

答案1

得分: 2

我倾向于使用嵌套处理程序。根处理程序处理"/",它弹出路径的第一部分,将剩余部分重新赋值给req.URL.Path(实际上就像StripPrefix一样),通过该前缀确定哪个处理程序处理路由(如果有的话),然后链接适当的处理程序。如果该处理程序需要从路径中解析出一个ID,它可以通过相同的机制 - 弹出路径的第一部分,根据需要进行解析,然后执行操作。

这不仅没有外部依赖,而且比任何路由器都要快,因为路由是硬编码的,而不是动态的。除非路由在运行时发生变化(这将非常不寻常),否则没有必要动态处理路由。

英文:

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.

答案2

得分: 1

这就是为什么人们使用像 gin-gonic 这样的框架,因为在 net/http 包中实现这个并不容易,如果我理解正确的话。

否则,你需要使用 strings.Split(r.URL.Path, "/") 并从这些元素中进行处理。

英文:

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.

答案3

得分: 0

使用net/http库,当调用localhost:8080/myapp/foo/entries/bar时,以下代码将被触发:

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

然后在yourHandlerFunction函数内部,手动解析r.URL.Path以找到foobar

请注意,如果不添加尾部的斜杠/,它将不起作用。以下代码只有在调用localhost:8080/myapp时才会触发:

http.HandleFunc("/myapp", yourHandlerFunction)
英文:

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)

huangapple
  • 本文由 发表于 2017年7月5日 15:42:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/44919927.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定