url.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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 // import "miniflux.app/url"
  5. import (
  6. "fmt"
  7. "net/url"
  8. "strings"
  9. )
  10. // IsAbsoluteURL returns true if the link is absolute.
  11. func IsAbsoluteURL(link string) bool {
  12. u, err := url.Parse(link)
  13. if err != nil {
  14. return false
  15. }
  16. return u.IsAbs()
  17. }
  18. // AbsoluteURL converts the input URL as absolute URL if necessary.
  19. func AbsoluteURL(baseURL, input string) (string, error) {
  20. if strings.HasPrefix(input, "//") {
  21. input = "https://" + input[2:]
  22. }
  23. u, err := url.Parse(input)
  24. if err != nil {
  25. return "", fmt.Errorf("unable to parse input URL: %v", err)
  26. }
  27. if u.IsAbs() {
  28. return u.String(), nil
  29. }
  30. base, err := url.Parse(baseURL)
  31. if err != nil {
  32. return "", fmt.Errorf("unable to parse base URL: %v", err)
  33. }
  34. return base.ResolveReference(u).String(), nil
  35. }
  36. // RootURL returns absolute URL without the path.
  37. func RootURL(websiteURL string) string {
  38. if strings.HasPrefix(websiteURL, "//") {
  39. websiteURL = "https://" + websiteURL[2:]
  40. }
  41. absoluteURL, err := AbsoluteURL(websiteURL, "")
  42. if err != nil {
  43. return websiteURL
  44. }
  45. u, err := url.Parse(absoluteURL)
  46. if err != nil {
  47. return absoluteURL
  48. }
  49. return u.Scheme + "://" + u.Host + "/"
  50. }
  51. // IsHTTPS returns true if the URL is using HTTPS.
  52. func IsHTTPS(websiteURL string) bool {
  53. parsedURL, err := url.Parse(websiteURL)
  54. if err != nil {
  55. return false
  56. }
  57. return strings.ToLower(parsedURL.Scheme) == "https"
  58. }
  59. // Domain returns only the domain part of the given URL.
  60. func Domain(websiteURL string) string {
  61. parsedURL, err := url.Parse(websiteURL)
  62. if err != nil {
  63. return websiteURL
  64. }
  65. return parsedURL.Host
  66. }