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 := "http://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 := "http://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
+5.4k Unix/Linux/MacOSx : Get local IP address
+15.3k Golang : How to convert(cast) IP address to string?
+22.4k Golang : Round float to precision example
+10.6k Golang : Command line file upload program to server example
+10.7k Golang : Simple image viewer with Go-GTK
+7.1k Golang : How to detect if a sentence ends with a punctuation?
+11.3k Golang : Change date format to yyyy-mm-dd
+10.2k Generate Random number with math/rand in Go
+10.4k Golang : Simple File Server
+5k PHP : See installed compiled-in-modules
+21.8k Golang : Convert seconds to minutes and remainder seconds
+6.4k Golang : Skip or discard items of non-interest when iterating example