-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathurl.go
57 lines (48 loc) · 1.42 KB
/
url.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package ghttp
import (
"fmt"
"net"
"net/url"
)
// ThisIsURL validates if a given URL has a valid scheme of either "http" or "https"
// and returns an error if not.
// It takes a string parameter, URL, representing the URL to be validated.
// Returns an error if the scheme is not valid, otherwise returns nil.
func ThisIsURL(URL string) error {
uri, err := url.ParseRequestURI(URL)
if err != nil {
return err
}
switch uri.Scheme {
case "http":
case "https":
default:
return fmt.Errorf("invalid scheme")
}
return nil
}
// ThisIsHostValid validates if a given URL has a valid host by performing a DNS lookup on the host.
// It takes a string parameter, URL, representing the URL to be validated.
// Returns an error if the host is not valid, otherwise returns nil.
func ThisIsHostValid(URL string) error {
uri, err := url.ParseRequestURI(URL)
if err != nil {
return err
}
_, err = net.LookupHost(uri.Host)
if err != nil {
return err
}
return nil
}
// GetHost extracts the host from a given URL and returns it as a string.
// It takes a string parameter, URL, representing the URL from which the host will be extracted.
// Returns the host as a string and nil error if the URL is successfully parsed.
// Returns an error message and the error itself if the URL parsing fails.
func GetHost(URL string) (string, error) {
uri, err := url.Parse(URL)
if err != nil {
return err.Error(), err
}
return uri.Host, nil
}