猿问

如何解析 /id/123 格式的 URL 而不是 ?foo=bar

我正在尝试解析如下 URL:

http://example.com/id/123

我已经通读了net/url文档,但它似乎只解析字符串

http://example.com/blah?id=123

我如何解析 ID 以便最终得到第一个示例中的 id 值?

这不是我自己的路由之一,而是从 openid 请求返回的 http 字符串。


ABOUTYOU
浏览 183回答 3
3回答

斯蒂芬大帝

这是一个简单的解决方案,适用于与您具有相同结构的 URL(您可以改进以适应具有其他结构的 URL)package mainimport (&nbsp; &nbsp; &nbsp; &nbsp;"fmt"&nbsp; &nbsp; &nbsp; &nbsp;"net/url")var path = "http://localhost:8080/id/123"func getFirstParam(path string) (ps string) {&nbsp; &nbsp; &nbsp;// ignore first '/' and when it hits the second '/'&nbsp; &nbsp; &nbsp;// get whatever is after it as a parameter&nbsp; &nbsp; &nbsp;for i := 1; i < len(path); i++ {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if path[i] == '/' {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ps = path[i+1:]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp;return}func main() {&nbsp; &nbsp; &nbsp;u, _ := url.Parse(path)&nbsp; &nbsp; &nbsp;fmt.Println(u.Path)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // -> "/id/123"&nbsp; &nbsp; &nbsp;fmt.Println(getFirstParam(u.Path)) // -> "123"}或者,正如@gollipher 建议的那样,使用path包import "path"func main() {&nbsp; &nbsp; u, _ := url.Parse(path)&nbsp; &nbsp; ps := path.Base(u.Path)}使用这种方法它比正则表达式更快,前提是您事先知道您获得的 URL 的结构。

子衿沉夜

您可以尝试使用正则表达式如下:import "regexp"re, _ := regexp.Compile("/id/(.*)")values := re.FindStringSubmatch(path)if len(values) > 0 {&nbsp; &nbsp; fmt.Println("ID : ", values[1])}
随时随地看视频慕课网APP

相关分类

Go
我要回答