This is just a quick post showing how we can check if a URL is a valid one. URLs are often passed from third parties or user input, so they need to be checked before used. This function allows you to do just that, it will return true if the string is a valid URL. Feel free to copy and paste it and go from there.
packagemainimport("fmt""net/url")funcmain(){myURL:="https://gophercoding.com/"ifisValidURL(myURL){fmt.Println(myURL,"is valid")}else{fmt.Println(myURL,"is not valid")}}// isValidURL checks if a given url matches a correct syntax of a webpage or URI
// by pre-parsing strings to make sure they are valid before attempting requests.
funcisValidURL(toTeststring)bool{u,err:=url.Parse(toTest)iferr!=nil||u.Scheme==""||u.Host==""{returnfalse}_,err=url.ParseRequestURI(toTest)iferr!=nil{returnfalse}returntrue}
Edd is a PHP and Go developer who enjoys blogging about his experiences, mostly about creating and coding new things he's working on and is a big beliver in open-source and Linux.