2022-10-14
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
*/
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)
}