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
+4.7k Linux/MacOSX : How to symlink a file?
+6.1k Fix ERROR 2003 (HY000): Can't connect to MySQL server on 'IP address' (111)
+5.1k Linux : How to set root password in Linux Mint
+11.3k Golang : How to use if, eq and print properly in html template
+9.4k Golang : Terminate-stay-resident or daemonize your program?
+8.2k Golang : HttpRouter multiplexer routing example
+10k Golang : Convert octal value to string to deal with leading zero problem
+12.3k Golang : List running EC2 instances and descriptions
+13.9k Generate salted password with OpenSSL example
+11.3k Golang : How to pipe input data to executing child process?
+26.9k Golang : Find files by extension
+17.7k Golang : Read data from config file and assign to variables