Go语言拼接URL路径的三种方法
Go语言拼接URL路径有多种方法建议用ResolveReference。
JoinPath
JoinPath会把多个多个路径合并成一个路径,并且处理../和./,多个//合并成单个/。
package main
import (
"fmt"
"net/url"
)
func main() {
u1 := "http://example.com/directory/"
u2 := "../../..//search?q=dotnet"
u3 := "/dir1/dir2/search?q=dotnet"
j1, _ := url.JoinPath(u1, u2)
j2, _ := url.JoinPath(u1, u3)
fmt.Println(j1)
// http://example.com/search%3Fq=dotnet
fmt.Println(j2)
// http://example.com/directory/dir1/dir2/search%3Fq=dotnet
}ResolveReference
ResolveReference会处理绝对路径和相对路径。
package main
import (
"fmt"
"log"
"net/url"
)
func main() {
u1, _ := url.Parse("../../..//search?q=dotnet")
u2, _ := url.Parse("/dir1/dir2/search?q=dotnet")
base, err := url.Parse("http://example.com/directory/")
if err != nil {
log.Fatal(err)
}
fmt.Println(base.ResolveReference(u1))
// http://example.com/search?q=dotnet
fmt.Println(base.ResolveReference(u2))
// http://example.com/dir1/dir2/search?q=dotnet
}path.Join
path主要是对斜杠放个的路径。
package main
import (
"fmt"
"log"
"net/url"
"path"
)
func main() {
u, err := url.Parse("http://example.com/test/")
if err != nil {
log.Fatal(err)
}
u.Path = path.Join(u.Path, "../bar.html")
s := u.String()
fmt.Println(s) // http://example.com/bar.html
}参考
https://pkg.go.dev/net/url@go1.19beta1#JoinPath
http://doc.golang.ltd/pkg/net_url.htm
到此这篇关于Go语言拼接URL路径的三种方法的文章就介绍到这了,更多相关Go语言拼接URL路径内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
关于golang中map使用的几点注意事项总结(强烈推荐!)
map是一种无序的基于key-value的数据结构,Go语言中的map是引用类型,必须初始化才能使用,下面这篇文章主要给大家介绍了关于golang中map使用的几点注意事项,需要的朋友可以参考下2023-01-01
详解golang避免循环import问题(“import cycle not allowed”)
这篇文章主要给大家介绍了关于golang中不允许循环import问题("import cycle not allowed")的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考借鉴,下面随着小编来一起学习学习吧2018-08-08
golang常用库之字段参数验证库-validator使用详解
这篇文章主要介绍了golang常用库:字段参数验证库-validator使用,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借价值,需要的朋友可以参考下2020-10-10


最新评论