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
+17.5k Golang : Parse date string and convert to dd-mm-yyyy format
+25.7k Golang : How to read integer value from standard input ?
+14.4k Golang : Send email with attachment(RFC2822) using Gmail API example
+5.9k PHP : How to check if an array is empty ?
+7.4k Golang : How to stop user from directly running an executable file?
+16.7k Golang : Set up source IP address before making HTTP request
+13.3k Golang : Generate Code128 barcode
+9.6k Golang : Eroding and dilating image with OpenCV example
+12.6k Golang : Drop cookie to visitor's browser and http.SetCookie() example
+5.3k Golang : Pad file extension automagically
+10.2k Golang : Convert file unix timestamp to UTC time example
+6.3k PHP : Proper way to get UTF-8 character or string length