Go语言拼接URL路径的三种方法
目录
- JoinPath
- ResolveReference
- path.Join
- 参考
Gojavascript语言拼接URL路径有多种方法建议用ResolveReference。
JoinPath
JoinPath会把多个多个路径合并成一个路径,并且处理../和./,多个//合并成单个/。
package main import ( "fmt" "net/开发者_JAVA入门url" ) func main() { u1 := "http://example.com/directory/" u2 := "../../..//search?q=dotnet" u3 := "/dir1/dir2/search?q=dotnet" j1, _ := url.Join编程Path(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会处理yhXpP绝对路径和相对路径。
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主要是对斜杠放个的路径。
pandroidackage 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路径内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!
精彩评论