rich_url.go 968 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package goreferrer
  2. import (
  3. "net/url"
  4. "strings"
  5. "golang.org/x/net/publicsuffix"
  6. )
  7. type richUrl struct {
  8. *url.URL
  9. Subdomain string
  10. Domain string
  11. Tld string
  12. }
  13. func parseRichUrl(s string) (*richUrl, bool) {
  14. u, err := url.Parse(s)
  15. if err != nil {
  16. return nil, false
  17. }
  18. // assume a default scheme of http://
  19. if u.Scheme == "" {
  20. s = "http://" + s
  21. u, err = url.Parse(s)
  22. if err != nil {
  23. return nil, false
  24. }
  25. }
  26. tld, _ := publicsuffix.PublicSuffix(u.Host)
  27. if tld == "" || len(u.Host)-len(tld) < 2 {
  28. return nil, false
  29. }
  30. hostWithoutTld := u.Host[:len(u.Host)-len(tld)-1]
  31. lastDot := strings.LastIndex(hostWithoutTld, ".")
  32. if lastDot == -1 {
  33. return &richUrl{URL: u, Domain: hostWithoutTld, Tld: tld}, true
  34. }
  35. return &richUrl{
  36. URL: u,
  37. Subdomain: hostWithoutTld[:lastDot],
  38. Domain: hostWithoutTld[lastDot+1:],
  39. Tld: tld,
  40. }, true
  41. }
  42. func (u *richUrl) RegisteredDomain() string {
  43. return u.Domain + "." + u.Tld
  44. }