如何正确解析URL

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

how to parse urls correctly

问题

当我想解析我的URL时,我遇到了以下错误:

panic: parse "http://x:SmT2fH": invalid port ":SmT2fH" after host

这是我的解析方式:

s := "http://x:S%40mT2fH#%25PVfTA5gjCtn@host:5432/default"

u, err := url.Parse(s)
if err != nil {
    panic(err)
}

fmt.Println(u)

我期望x是用户名,S%40mT2fH#%25PVfTA5gjCtn是密码。
但错误提示说它是一个无效的端口,因为它不是一个端口。

有人知道问题是什么吗?

英文:

When I want to parse my url I get the following error:

panic: parse "http://x:SmT2fH": invalid port ":SmT2fH" after host

This is how I parse it:

s := "http://x:S%40mT2fH#%25PVfTA5gjCtn@host:5432/default"

u, err := url.Parse(s)
if err != nil {
	panic(err)
}

fmt.Println(u)

I expect x to be user and S%40mT2fH#%25PVfTA5gjCtn to be password.
But the errors say that it's an invalid port. because it's not port.

Does anyone know the problem?

答案1

得分: 1

你需要转义字面量#,因为在URL中它被“保留”,用于指示片段组件的开始。

转义代码是%23

func main() {
	u, err := url.Parse("http://x:S%40mT2fH%23%25PVfTA5gjCtn@host:5432/default")
	if err != nil {
		panic(err)
	}

	fmt.Println(u)
	fmt.Printf("%#v\n", u.User)
}

https://go.dev/play/p/xMHX-gvqhqj

英文:

You need to escape the literal # as it is "reserved" by URL for indicating the start of the fragment component.

The escape code is %23.

func main() {
	u, err := url.Parse("http://x:S%40mT2fH%23%25PVfTA5gjCtn@host:5432/default")
	if err != nil {
		panic(err)
	}

	fmt.Println(u)
	fmt.Printf("%#v\n", u.User)
}

https://go.dev/play/p/xMHX-gvqhqj

huangapple
  • 本文由 发表于 2022年9月4日 20:29:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/73599402.html
匿名

发表评论

匿名网友

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

确定