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.

url.go 1.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  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. )
  10. // PathEscapeSegments escapes segments of a path while not escaping forward slash
  11. func PathEscapeSegments(path string) string {
  12. slice := strings.Split(path, "/")
  13. for index := range slice {
  14. slice[index] = url.PathEscape(slice[index])
  15. }
  16. escapedPath := strings.Join(slice, "/")
  17. return escapedPath
  18. }
  19. // URLJoin joins url components, like path.Join, but preserving contents
  20. func URLJoin(base string, elems ...string) string {
  21. if !strings.HasSuffix(base, "/") {
  22. base += "/"
  23. }
  24. baseURL, err := url.Parse(base)
  25. if err != nil {
  26. return ""
  27. }
  28. joinedPath := path.Join(elems...)
  29. argURL, err := url.Parse(joinedPath)
  30. if err != nil {
  31. return ""
  32. }
  33. joinedURL := baseURL.ResolveReference(argURL).String()
  34. if !baseURL.IsAbs() && !strings.HasPrefix(base, "/") {
  35. return joinedURL[1:] // Removing leading '/' if needed
  36. }
  37. return joinedURL
  38. }