Golang解析、验证、修改URL之Host、Port、Path

  • URL解析验证问题
    • net.ParseIP()只能解析不带冒号以及端口号的IP4/IP6
      • ✔: 127.0.0.12001:db8::68
      • ✖: 127.0.0.1:8080www.baidu.com
    • url.Parse()最好只用来解析标准URL,不能用来验证URL的正确性

func main() {
	IP1 := "www.baidu.com"
	IP2 := "127.0.0.1"
	IP3 := "127.0.0.1:8080"
	parsedIP1 := net.ParseIP(IP1)
	parsedIP2 := net.ParseIP(IP2)
	parsedIP3 := net.ParseIP(IP3)
	fmt.Println("net.ParseIP: ", parsedIP1, parsedIP2, parsedIP3)

	fmt.Println()

	Url1 := "127.0.0"
	Url2 := "abc"
	Url3 := "127.0.0.1:8080"
	Url4 := "http://127.0.0.1:8080/url"

	parsedUrl1, err := url.Parse(Url1)
	if err != nil {
		fmt.Println("Error: ", err)
	}
	parsedUrl2, err := url.Parse(Url2)
	if err != nil {
		fmt.Println("Error: ", err)
	}
	parsedUrl3, err := url.Parse(Url3)
	if err != nil {
		fmt.Println("Error: ", err)
	}
	parsedUrl4, err := url.Parse(Url4)
	if err != nil {
		fmt.Println("Error: ", err)
	}
	fmt.Println("1: ", parsedUrl1, "2: ", parsedUrl2, "3: ", parsedUrl3, "4: ", parsedUrl4)
}
/*
输出结果:
net.ParseIP:  <nil> 127.0.0.1 <nil>

Error:  parse 127.0.0.1:8080: first path segment in URL cannot contain colon
1:  127.0.0 2:  abc 3:  <nil> 4:  http://127.0.0.1:8080/url

*/
  • 正确的URL验证方式

    • go get github.com/asaskevich/govalidator
    • govalidator.IsURL()
  • 获取并修改URL之Host、Port、Path

func main() {
	rawUrl := "http://127.0.0.1:8080/url/123"
	changeHost := "192.168.1.1"

	newUrl, _ := url.Parse(rawUrl)

	// Host
	newUrlHost := newUrl.Hostname()
	// Port
	newUrlPort := newUrl.Port()
	// Path
	newUrlPath := newUrl.Path
	// URL类型转string
	stringUrl := newUrl.String()
	// 修改URl Host
	newUrl.Host = changeHost + ":" + newUrl.Port()

	fmt.Println(newUrlHost, newUrlPort, newUrlPath, stringUrl, newUrl)
}

其他相关方法:

  • Host、Port
    • net.SplitHostPort() ==> Host、Port、error
    • u := strings.Split(url, ":") ==> Host := u[0]
  • Path
    • url := http://www.a.com/123 ==> base := path.Base(url)
    • fmt.Println(base) ==> 123

以上结合可完成关于Golang操作URL的大部分问题

posted on 2019-09-05 19:04  GaiheiluKamei  阅读(6677)  评论(0编辑  收藏  举报

导航