Passed
Push — main ( add42e...815f74 )
by Rushan
02:28 queued 12s
created

validate.URL   A

Complexity

Conditions 5

Size

Total Lines 19
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 12
dl 0
loc 19
rs 9.3333
c 0
b 0
f 0
nop 2
1
package validate
2
3
import (
4
	"errors"
5
	"net/url"
6
)
7
8
var (
9
	ErrUnexpectedSchema = errors.New("unexpected schema")
10
)
11
12
// URL is used to validate that value is a valid URL string. By default (if no schemas are passed),
13
// the function checks only for the http:// and https:// schemas. Use the schemas argument
14
// to configure the list of expected schemas. If an empty string is passed as a schema, then
15
// URL value may be treated as relative (without schema, e.g. "//example.com").
16
//
17
// If value is not a valid URL the function will return one of the errors:
18
//	• parsing error from url.Parse method if value cannot be parsed as an URL;
19
//	• ErrUnexpectedSchema if schema is not matching one of the listed schemas;
20
//	• ErrInvalid if value is not matching the regular expression.
21
func URL(value string, schemas ...string) error {
22
	if len(schemas) == 0 {
23
		schemas = []string{"http", "https"}
24
	}
25
	u, err := url.Parse(value)
26
	if err != nil {
27
		return err
28
	}
29
30
	err = validateSchema(u, schemas)
31
	if err != nil {
32
		return err
33
	}
34
35
	if !urlRegex.MatchString(value) {
36
		return ErrInvalid
37
	}
38
39
	return nil
40
}
41
42
func validateSchema(u *url.URL, schemas []string) error {
43
	for _, schema := range schemas {
44
		if schema == u.Scheme {
45
			return nil
46
		}
47
	}
48
49
	return ErrUnexpectedSchema
50
}
51