本站源代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 lines
1.6KB

  1. // Copyright 2019 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package util
  5. import (
  6. "net/url"
  7. "path"
  8. "strings"
  9. "code.gitea.io/gitea/modules/log"
  10. "code.gitea.io/gitea/modules/setting"
  11. )
  12. // PathEscapeSegments escapes segments of a path while not escaping forward slash
  13. func PathEscapeSegments(path string) string {
  14. slice := strings.Split(path, "/")
  15. for index := range slice {
  16. slice[index] = url.PathEscape(slice[index])
  17. }
  18. escapedPath := strings.Join(slice, "/")
  19. return escapedPath
  20. }
  21. // URLJoin joins url components, like path.Join, but preserving contents
  22. func URLJoin(base string, elems ...string) string {
  23. if !strings.HasSuffix(base, "/") {
  24. base += "/"
  25. }
  26. baseURL, err := url.Parse(base)
  27. if err != nil {
  28. log.Error("URLJoin: Invalid base URL %s", base)
  29. return ""
  30. }
  31. joinedPath := path.Join(elems...)
  32. argURL, err := url.Parse(joinedPath)
  33. if err != nil {
  34. log.Error("URLJoin: Invalid arg %s", joinedPath)
  35. return ""
  36. }
  37. joinedURL := baseURL.ResolveReference(argURL).String()
  38. if !baseURL.IsAbs() && !strings.HasPrefix(base, "/") {
  39. return joinedURL[1:] // Removing leading '/' if needed
  40. }
  41. return joinedURL
  42. }
  43. // IsExternalURL checks if rawURL points to an external URL like http://example.com
  44. func IsExternalURL(rawURL string) bool {
  45. parsed, err := url.Parse(rawURL)
  46. if err != nil {
  47. return true
  48. }
  49. appURL, _ := url.Parse(setting.AppURL)
  50. if len(parsed.Host) != 0 && strings.Replace(parsed.Host, "www.", "", 1) != strings.Replace(appURL.Host, "www.", "", 1) {
  51. return true
  52. }
  53. return false
  54. }
上海开阖软件有限公司 沪ICP备12045867号-1