validate a url in go

To validate a URL in Go, you can make use of the url.Parse() function from the net/url package. Here's an example:

main.go
package main

import (
	"fmt"
	"net/url"
)

func main() {
	// URL to be validated
	urlStr := "https://www.example.com"

	// Parse the URL
	parsedURL, err := url.Parse(urlStr)
	if err != nil {
		fmt.Println("Invalid URL")
		return
	}

	// Check if the scheme and host are valid
	if parsedURL.Scheme == "" || parsedURL.Host == "" {
		fmt.Println("Invalid URL")
		return
	}

	fmt.Println("URL is valid")
}
403 chars
27 lines

In the above code, we use the url.Parse() function to parse the URL string provided. If the URL is invalid, url.Parse() returns an error. We then check if the scheme and host of the parsed URL are empty, which indicates an invalid URL.

Note that this validation does not ensure that the URL is reachable or that it points to an existing resource. It simply checks the basic components of a URL such as the scheme and host.

Keep in mind that this validation method may not handle all possible edge cases, as URL validation can be complex. Depending on your specific requirements, you may need to implement additional checks or use a more advanced validation library.

related categories

gistlibby LogSnag