ExtractDomainFromURL extracts the domain name from a URL string. Handles various URL formats including full URLs with protocols, URLs with ports, and plain domain names. This function uses net/url.Parse for proper URL parsing when a protocol is present, and falls back to string manipulation for oth
(urlStr string)
| 39 | // ExtractDomainFromURL("http://sub.domain.com:8080/path") // returns "sub.domain.com" |
| 40 | // ExtractDomainFromURL("localhost:8080") // returns "localhost" |
| 41 | func ExtractDomainFromURL(urlStr string) string { |
| 42 | urlsLog.Printf("Extracting domain from URL: %s", urlStr) |
| 43 | // Handle full URLs with protocols (http://, https://) |
| 44 | if strings.HasPrefix(urlStr, "http://") || strings.HasPrefix(urlStr, "https://") { |
| 45 | // Parse full URL |
| 46 | parsedURL, err := url.Parse(urlStr) |
| 47 | if err != nil { |
| 48 | // Fall back to string manipulation if parsing fails |
| 49 | urlsLog.Printf("URL parse failed, using fallback: %v", err) |
| 50 | return extractDomainFallback(urlStr) |
| 51 | } |
| 52 | return parsedURL.Hostname() |
| 53 | } |
| 54 | |
| 55 | // For URLs without protocol, use string manipulation |
| 56 | return extractDomainFallback(urlStr) |
| 57 | } |
| 58 | |
| 59 | // extractDomainFallback extracts domain using string manipulation. |
| 60 | // This handles URLs without protocols, CONNECT requests (domain:port format), |