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

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

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

问题

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

  1. package main
  2. import (
  3. "fmt"
  4. "net/url"
  5. "path"
  6. )
  7. func main() {
  8. u, _ := url.Parse("http://localhost:5100")
  9. relative, _ := url.Parse(path.Join("hello/"))
  10. fmt.Println(u.ResolveReference(relative))
  11. }

输出结果:

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

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

  1. package main
  2. import (
  3. "fmt"
  4. "net/url"
  5. "path"
  6. )
  7. func main() {
  8. u, _ := url.Parse("http://localhost:5100")
  9. relative, _ := url.Parse(path.Join("hello/"))
  10. fmt.Println(u.ResolveReference(relative))
  11. }

Output:

  1. http://localhost:5100/hello

答案1

得分: 1

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

  1. package main
  2. import (
  3. "fmt"
  4. "net/url"
  5. )
  6. func main() {
  7. u, _ := url.Parse("http://localhost:5100")
  8. relative, _ := url.Parse("hello/")
  9. fmt.Println(u.ResolveReference(relative))
  10. }

输出结果:

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

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

  1. package main
  2. import (
  3. "fmt"
  4. "net/url"
  5. )
  6. func main() {
  7. u, _ := url.Parse("http://localhost:5100")
  8. relative, _ := url.Parse("hello/")
  9. fmt.Println(u.ResolveReference(relative))
  10. }

Output:

  1. 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:

确定