如何在Go中使用ResolveReference时避免删除URL末尾的斜杠?

huangapple go评论96阅读模式
英文:

How to avoid end of URL slash being removed when ResolveReference in Go

问题

在下面的示例中,URL的末尾/被删除了,有没有办法保留/

package main

import (
	"fmt"
	"net/url"
	"path"
)

func main() {
	u, _ := url.Parse("http://localhost:5100")
	relative, _ := url.Parse(path.Join("hello/"))
	fmt.Println(u.ResolveReference(relative))
}

输出结果:

http://localhost:5100/hello
英文:

In the following example, end of URL / is removed, is there a way to keep the /?

package main

import (
	"fmt"
	"net/url"
	"path"
)

func main() {
	u, _ := url.Parse("http://localhost:5100")
	relative, _ := url.Parse(path.Join("hello/"))
	fmt.Println(u.ResolveReference(relative))
}

Output:

http://localhost:5100/hello

答案1

得分: 1

我找到了答案,就是不使用path.Join函数:

package main

import (
	"fmt"
	"net/url"
)

func main() {
	u, _ := url.Parse("http://localhost:5100")
	relative, _ := url.Parse("hello/")
	fmt.Println(u.ResolveReference(relative))
}

输出结果:

http://localhost:5100/hello/
英文:

I figured out the answer, which is not to use path.Join:

package main

import (
	"fmt"
	"net/url"
)

func main() {
	u, _ := url.Parse("http://localhost:5100")
	relative, _ := url.Parse("hello/")
	fmt.Println(u.ResolveReference(relative))
}

Output:

http://localhost:5100/hello/

huangapple
  • 本文由 发表于 2014年4月14日 11:08:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/23051339.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定