小编典典

将 URL 路径与 path.Join() 结合

go

在 Go 中有没有办法像使用文件路径一样组合 URL 路径path.Join()

当我使用时path.Join("http://foo", "bar"),我得到http:/foo/bar.

参见Golang Playground


阅读 250

收藏
2021-12-26

共1个答案

小编典典

函数 path.Join 需要一个路径,而不是一个 URL。解析 URL 以获取路径并加入该路径:

u, err := url.Parse("http://foo")
u.Path = path.Join(u.Path, "bar.html")
s := u.String() // prints http://foo/bar.html

playground example

如果您组合的不仅仅是路径(例如方案或主机)或字符串多于路径(例如它包括查询字符串),则使用ResolveReference

2021-12-26