0

I want to validate a image url that my code will accept the that image url which having http and https if there is any other url is present that would not be accepted for example:-

fnc main(){
   var url1,url2,url3 string
   url1 = "/image.png" // not accepted
   url2 = "http://abc/image.jpg"  // accepted
   url3 = "https://abc/image.jpg" // accepted
}

What regular expression is used for this validation?

user10665991
  • 73
  • 1
  • 3
  • 10
  • Possible duplicate of [Regex to check if valid URL that ends in .jpg, .png, or .gif](https://stackoverflow.com/questions/169625/regex-to-check-if-valid-url-that-ends-in-jpg-png-or-gif) – CallMeLoki Nov 17 '18 at 07:23

2 Answers2

2

If your criteria is just "having http", you can simply use the strings.HasPrefix:

if strings.HasPrefix(url1, "http://") || strings.HasPrefix(url1, "https://") {
    // Valid URL
}

However, you can use the url.Parse and check the scheme:

uri, err := url.Parse(url1)
if err != nil && uri.Scheme != "http" && uri.Scheme != "https" {
    // Error
}

// Valid URL
Inkeliz
  • 892
  • 1
  • 13
  • 25
0
matched, err := regexp.MatchString("^http.*://", "https://www.google.com")

Goplayground Example