如何使用Go优雅地解析URI?

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

How to parse URI gracefully using Go?

问题

这是我在etcd中的kafka连接信息:

kafka://user:passwd@10.10.172.222:9092?mechanism=PLAIN&protocol=SASL_PLAINTEXT

当我从etcd获取到这个信息字符串后,我想要提取出用户名user、密码passwd和主机10.10.172.222:9092

现在我该如何使用Golang优雅地解析Kafka连接信息呢?

英文:

Here is my kafka connection information in etcd :

kafka://user:passwd@10.10.172.222:9092?mechanism=PLAIN&protocol=SASL_PLAINTEXT

When i get the information string from the etcd, i want to get the username user,password passwd and host 10.10.172.222:9092.

Now how can i parse Kafka connection information gracefully using Golang?

答案1

得分: 4

使用net/url

kafkaUrl := "kafka://user@10.10.172.222:9092?mechanism=PLAIN&protocol=SASL_PLAINTEXT"

u, err := url.Parse(kafkaUrl)
if err != nil {
	// 处理错误
}
user := u.User.Username()
pass, isPassSet := u.User.Password()
host := u.Host // 主机或主机:端口

分别获取主机名和端口

hostname := u.Hostname()
port := u.Port()
英文:

Use net/url library

kafkaUrl := "kafka://user@10.10.172.222:9092?mechanism=PLAIN&protocol=SASL_PLAINTEXT"

u, err := url.Parse(kafkaUrl)
if err != nil {
	// handle error
}
user := u.User.Username()
pass, isPassSet := u.User.Password()
host := u.Host // host or host:port

hostname and port separetely

hostname := u.Hostname()
port := u.Port()

huangapple
  • 本文由 发表于 2021年10月22日 17:58:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/69674872.html
匿名

发表评论

匿名网友

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

确定