Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to check if a string is a valid URL in Golang?
There are cases where we would want to know if the URL that we got from an http request in the form of a string is even valid or not. In such cases, one can use two functions that the net/url package of Go's standard library provides.
Example 1
The first basic case is to check if the URL is well structured and a valid one, and for that, we can use the ParseRequestURI() function of the URL package.
Consider the code shown below.
package main
import (
"fmt"
"net/url"
)
func main() {
u, err := url.ParseRequestURI("http://golangcode.com")
if err != nil {
panic(err)
}
fmt.Println(u)
}
Output
If we run the command go run main.go on the above code, then we will get the following output in the terminal.
http://golangcode.com
In the above code, we passed a valid URL with a host and the scheme and if we change it to an invalid one, we will get an error.
Example 2
Consider the code shown below.
package main
import (
"fmt"
"net/url"
)
func main() {
u, err := url.ParseRequestURI("golangcode.com")
if err != nil {
panic(err)
}
fmt.Println(u)
}
Output
If we run the command go run main.go on the above code, then we will get the following output in the terminal.
panic: parse "golangcode.com": invalid URI for request
There's a catch when using ParseRequestURI() and that is, it considers that the URL was received in an HTTP Request, which can lead to some inconsistencies.
If we pass "Test:Test" string as the argument to the ParseRequestURI() function, then it will not yield any error. So, a better option is to make use of the Parse function along with the ParseRequestURI().
Example 3
Consider the code shown below.
package main
import (
"fmt"
"net/url"
)
func main() {
_, err := url.ParseRequestURI("http://www.google.com")
if err != nil {
panic(err)
}
u, err := url.Parse("http://www.google.com")
if err != nil || u.Scheme == "" || u.Host == "" {
panic(err)
}
fmt.Println("All ok")
}
Output
If we run the command go run main.go on the above code, then we will get the following output in the terminal.
All Ok
