|
| 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 | + |
| 5 | +package util |
| 6 | + |
| 7 | +import ( |
| 8 | + "net/url" |
| 9 | + "path" |
| 10 | + "strings" |
| 11 | + |
| 12 | + "code.gitea.io/gitea/modules/log" |
| 13 | + "code.gitea.io/gitea/modules/setting" |
| 14 | +) |
| 15 | + |
| 16 | +// PathEscapeSegments escapes segments of a path while not escaping forward slash |
| 17 | +func PathEscapeSegments(path string) string { |
| 18 | + slice := strings.Split(path, "/") |
| 19 | + for index := range slice { |
| 20 | + slice[index] = url.PathEscape(slice[index]) |
| 21 | + } |
| 22 | + escapedPath := strings.Join(slice, "/") |
| 23 | + return escapedPath |
| 24 | +} |
| 25 | + |
| 26 | +// URLJoin joins url components, like path.Join, but preserving contents |
| 27 | +func URLJoin(base string, elems ...string) string { |
| 28 | + if !strings.HasSuffix(base, "/") { |
| 29 | + base += "/" |
| 30 | + } |
| 31 | + baseURL, err := url.Parse(base) |
| 32 | + if err != nil { |
| 33 | + log.Error(4, "URLJoin: Invalid base URL %s", base) |
| 34 | + return "" |
| 35 | + } |
| 36 | + joinedPath := path.Join(elems...) |
| 37 | + argURL, err := url.Parse(joinedPath) |
| 38 | + if err != nil { |
| 39 | + log.Error(4, "URLJoin: Invalid arg %s", joinedPath) |
| 40 | + return "" |
| 41 | + } |
| 42 | + joinedURL := baseURL.ResolveReference(argURL).String() |
| 43 | + if !baseURL.IsAbs() && !strings.HasPrefix(base, "/") { |
| 44 | + return joinedURL[1:] // Removing leading '/' if needed |
| 45 | + } |
| 46 | + return joinedURL |
| 47 | +} |
| 48 | + |
| 49 | +// IsExternalURL checks if rawURL points to an external URL like http://example.com |
| 50 | +func IsExternalURL(rawURL string) bool { |
| 51 | + parsed, err := url.Parse(rawURL) |
| 52 | + if err != nil { |
| 53 | + return true |
| 54 | + } |
| 55 | + if len(parsed.Host) != 0 && strings.Replace(parsed.Host, "www.", "", 1) != strings.Replace(setting.Domain, "www.", "", 1) { |
| 56 | + return true |
| 57 | + } |
| 58 | + return false |
| 59 | +} |
0 commit comments