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.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. // Copyright 2019 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package util
  4. import (
  5. "net/url"
  6. "path"
  7. "strings"
  8. )
  9. // PathEscapeSegments escapes segments of a path while not escaping forward slash
  10. func PathEscapeSegments(path string) string {
  11. slice := strings.Split(path, "/")
  12. for index := range slice {
  13. slice[index] = url.PathEscape(slice[index])
  14. }
  15. escapedPath := strings.Join(slice, "/")
  16. return escapedPath
  17. }
  18. // URLJoin joins url components, like path.Join, but preserving contents
  19. func URLJoin(base string, elems ...string) string {
  20. if !strings.HasSuffix(base, "/") {
  21. base += "/"
  22. }
  23. baseURL, err := url.Parse(base)
  24. if err != nil {
  25. return ""
  26. }
  27. joinedPath := path.Join(elems...)
  28. argURL, err := url.Parse(joinedPath)
  29. if err != nil {
  30. return ""
  31. }
  32. joinedURL := baseURL.ResolveReference(argURL).String()
  33. if !baseURL.IsAbs() && !strings.HasPrefix(base, "/") {
  34. return joinedURL[1:] // Removing leading '/' if needed
  35. }
  36. return joinedURL
  37. }
  38. func SanitizeURL(s string) (string, error) {
  39. u, err := url.Parse(s)
  40. if err != nil {
  41. return "", err
  42. }
  43. u.User = nil
  44. return u.String(), nil
  45. }