Golang : How to validate URL the right way
Validating input from user or external sources is critical and needed to ensure that your program will not simply process 'garbage' data. You know, garbage in, garbage out.
I've seen many programmers use the net/url.Parse()
function returning error message as the way to validate URL. However, it is NOT the right way and why you should use a better URL validator, such as govalidator package to validate a URL.
Typically a Golang developer validates an URL with net/url.Parse()
function. Such as the code below.
package main
import (
"fmt"
"net/url"
)
func main() {
str := "//socketloop.com"
var validURL bool
_, err := url.Parse(str)
if err != nil {
fmt.Println(err)
validURL = false
} else {
validURL = true
}
fmt.Printf("%s is a valid URL : %v \n", str, validURL)
}
This method has many weaknesses and if you change the str
value to d or wwwsocketloopcom, net/url.Parse()
function will still pass the broken URL as valid. This is NOT the right way to validate URL.
To validate an URL properly, use the IsURL()
function from github.com/asaskevich/govalidator
package.
package main
import (
"fmt"
"github.com/asaskevich/govalidator"
)
func main() {
str := "//www.socketloop.com"
validURL := govalidator.IsURL(str)
fmt.Printf("%s is a valid URL : %v \n", str, validURL)
}
Play around by changing the input URL and you will see that this method is more robust than the previous code.
References :
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+21.6k Golang : Gorilla mux routing example
+21k Golang : Read a file into an array or slice example
+5.5k Golang : How to setup a disk space used monitoring service with Telegram bot
+4.6k Swift : Get substring with rangeOfString() function example
+12.8k Golang : ROT47 (Caesar cipher by 47 characters) example
+14.5k Golang : Update database with GORM example
+12.4k Golang : Reverse IP address for reverse DNS lookup example
+23.6k Golang : Storing cookies in http.CookieJar example
+14.3k Chrome : ERR_INSECURE_RESPONSE and allow Chrome browser to load insecure content
+5.7k CloudFlare : Another way to get visitor's real IP address
+18.8k Golang : Count number of digits from given integer value
+5.2k PHP : Proper way to get UTF-8 character or string length