url.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // Copyright 2017 Frédéric Guillot. All rights reserved.
  2. // Use of this source code is governed by the Apache 2.0
  3. // license that can be found in the LICENSE file.
  4. package url
  5. import "net/url"
  6. import "fmt"
  7. import "strings"
  8. // AbsoluteURL converts the input URL as absolute URL if necessary.
  9. func AbsoluteURL(baseURL, input string) (string, error) {
  10. if strings.HasPrefix(input, "//") {
  11. input = "https://" + input[2:]
  12. }
  13. u, err := url.Parse(input)
  14. if err != nil {
  15. return "", fmt.Errorf("unable to parse input URL: %v", err)
  16. }
  17. if u.IsAbs() {
  18. return u.String(), nil
  19. }
  20. base, err := url.Parse(baseURL)
  21. if err != nil {
  22. return "", fmt.Errorf("unable to parse base URL: %v", err)
  23. }
  24. return base.ResolveReference(u).String(), nil
  25. }
  26. // RootURL returns absolute URL without the path.
  27. func RootURL(websiteURL string) string {
  28. if strings.HasPrefix(websiteURL, "//") {
  29. websiteURL = "https://" + websiteURL[2:]
  30. }
  31. absoluteURL, err := AbsoluteURL(websiteURL, "")
  32. if err != nil {
  33. return websiteURL
  34. }
  35. u, err := url.Parse(absoluteURL)
  36. if err != nil {
  37. return absoluteURL
  38. }
  39. return u.Scheme + "://" + u.Host + "/"
  40. }
  41. // IsHTTPS returns true if the URL is using HTTPS.
  42. func IsHTTPS(websiteURL string) bool {
  43. parsedURL, err := url.Parse(websiteURL)
  44. if err != nil {
  45. return false
  46. }
  47. return strings.ToLower(parsedURL.Scheme) == "https"
  48. }
  49. // Domain returns only the domain part of the given URL.
  50. func Domain(websiteURL string) string {
  51. parsedURL, err := url.Parse(websiteURL)
  52. if err != nil {
  53. return websiteURL
  54. }
  55. return parsedURL.Host
  56. }