英文:
How do I parse URLs in the format of /id/123 not ?foo=bar
问题
我正在尝试解析一个像这样的URL:
我已经阅读了net/url
文档,但似乎它只能解析像这样的字符串:
http://example.com/blah?id=123
我该如何解析ID,以便在第一个示例中得到id的值?
这不是我自己的路由,而是从一个openid请求返回的http字符串。
英文:
I'm trying to parse an URL like:
I've read through the net/url
docs but it seems like it only parses strings like
http://example.com/blah?id=123
How can I parse the ID so I end up with the value of the id in the first example?
This is not one of my own routes but a http string returned from an openid request.
答案1
得分: 16
在你的示例中,/id/123是一个路径,你可以使用路径模块的Base函数来获取"123"部分。
package main
import (
"fmt"
"path"
)
func main() {
fmt.Println(path.Base("/id/123"))
}
为了方便参考,这是路径模块的文档:http://golang.org/pkg/path/#example_Base
英文:
In your example /id/123 is a path and you can get the "123" part by using Base from the path module.
package main
import (
"fmt"
"path"
)
func main() {
fmt.Println(path.Base("/id/123"))
}
For easy reference, here's the docs on the path module. http://golang.org/pkg/path/#example_Base
答案2
得分: 8
你可以尝试使用以下正则表达式:
import "regexp"
re, _ := regexp.Compile("/id/(.*)")
values := re.FindStringSubmatch(path)
if len(values) > 0 {
fmt.Println("ID : ", values[1])
}
这段代码使用了正则表达式来匹配路径中的ID。如果匹配成功,它会打印出ID的值。
英文:
You can try using regular expression as follow:
import "regexp"
re, _ := regexp.Compile("/id/(.*)")
values := re.FindStringSubmatch(path)
if len(values) > 0 {
fmt.Println("ID : ", values[1])
}
答案3
得分: 3
以下是翻译好的内容:
这是一个适用于与您的URL具有相同结构的简单解决方案(您可以根据其他结构进行改进)。
package main
import (
"fmt"
"net/url"
)
var path = "http://localhost:8080/id/123"
func getFirstParam(path string) (ps string) {
// 忽略第一个'/',并在第二个'/'出现时获取其后的内容作为参数
for i := 1; i < len(path); i++ {
if path[i] == '/' {
ps = path[i+1:]
}
}
return
}
func main() {
u, _ := url.Parse(path)
fmt.Println(u.Path) // -> "/id/123"
fmt.Println(getFirstParam(u.Path)) // -> "123"
}
或者,如@gollipher建议的那样,使用path
包:
import "path"
func main() {
u, _ := url.Parse(path)
ps := path.Base(u.Path)
}
使用这种方法比正则表达式更快,前提是您事先知道所获取的URL的结构。
英文:
Here is a simple solution that works for URLs with the same structure as yours (you can improve to suit those with other structures)
package main
import (
"fmt"
"net/url"
)
var path = "http://localhost:8080/id/123"
func getFirstParam(path string) (ps string) {
// ignore first '/' and when it hits the second '/'
// get whatever is after it as a parameter
for i := 1; i < len(path); i++ {
if path[i] == '/' {
ps = path[i+1:]
}
}
return
}
func main() {
u, _ := url.Parse(path)
fmt.Println(u.Path) // -> "/id/123"
fmt.Println(getFirstParam(u.Path)) // -> "123"
}
Or, as @gollipher suggested, use the path
package
import "path"
func main() {
u, _ := url.Parse(path)
ps := path.Base(u.Path)
}
With this method it's faster than regex, provided you know before hand the structure of the URL you are getting.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论