url.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. // GetAbsoluteURL converts the input URL as absolute URL if necessary.
  9. func GetAbsoluteURL(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. // GetRootURL returns absolute URL without the path.
  27. func GetRootURL(websiteURL string) string {
  28. if strings.HasPrefix(websiteURL, "//") {
  29. websiteURL = "https://" + websiteURL[2:]
  30. }
  31. absoluteURL, err := GetAbsoluteURL(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. }