code.gitea.io/gitea@v1.19.3/modules/util/url.go (about) 1 // Copyright 2019 The Gitea Authors. All rights reserved. 2 // SPDX-License-Identifier: MIT 3 4 package util 5 6 import ( 7 "net/url" 8 "path" 9 "strings" 10 ) 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 22 // URLJoin joins url components, like path.Join, but preserving contents 23 func URLJoin(base string, elems ...string) string { 24 if !strings.HasSuffix(base, "/") { 25 base += "/" 26 } 27 baseURL, err := url.Parse(base) 28 if err != nil { 29 return "" 30 } 31 joinedPath := path.Join(elems...) 32 argURL, err := url.Parse(joinedPath) 33 if err != nil { 34 return "" 35 } 36 joinedURL := baseURL.ResolveReference(argURL).String() 37 if !baseURL.IsAbs() && !strings.HasPrefix(base, "/") { 38 return joinedURL[1:] // Removing leading '/' if needed 39 } 40 return joinedURL 41 }