How to Check if a String is a Valid URL in Go

Created
Modified

Using ParseRequestURI Function

url.ParseRequestURI parses a raw url into a URL structure. It assumes that url was received in an HTTP request, so the url is interpreted only as an absolute URI or an absolute path. The string url is assumed not to have a #fragment suffix.

See the following example:

package main

import (
  "fmt"
  "net/url"
)

func main() {
  s := "http//google.com"

  _, err := url.ParseRequestURI(s)
  if err != nil {
    // invalid
    fmt.Println(err)
  }
}
parse "http//google.com": invalid URI for request

Using Parse Function

The url.Parse() function parses a raw url into a URL structure. For example,

package main

import (
  "fmt"
  "net/url"
)

func IsUrl(str string) bool {
  u, err := url.Parse(str)
  return err == nil && u.Scheme != "" && u.Host != ""
}

func main() {
  s := "http//google.com"

  fmt.Println(IsUrl(s))
}
false

Related Tags