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 5package util 6 7import ( 8 "net/url" 9 "path" 10 "strings" 11) 12 13// PathEscapeSegments escapes segments of a path while not escaping forward slash 14func PathEscapeSegments(path string) string { 15 slice := strings.Split(path, "/") 16 for index := range slice { 17 slice[index] = url.PathEscape(slice[index]) 18 } 19 escapedPath := strings.Join(slice, "/") 20 return escapedPath 21} 22 23// URLJoin joins url components, like path.Join, but preserving contents 24func URLJoin(base string, elems ...string) string { 25 if !strings.HasSuffix(base, "/") { 26 base += "/" 27 } 28 baseURL, err := url.Parse(base) 29 if err != nil { 30 return "" 31 } 32 joinedPath := path.Join(elems...) 33 argURL, err := url.Parse(joinedPath) 34 if err != nil { 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