Golang

关注公众号 jb51net

关闭
首页 > 脚本专栏 > Golang > Go语言拼接URL路径

Go语言拼接URL路径的三种方法

作者:小龙在山东

本文主要介绍了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路径内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文