github.com/vmware/transport-go@v1.3.4/plank/utils/uri.go (about) 1 // Copyright 2019-2021 VMware, Inc. 2 // SPDX-License-Identifier: BSD-2-Clause 3 4 package utils 5 6 import ( 7 "regexp" 8 "strings" 9 ) 10 11 // SanitizeUrl removes excess forward slashes as well as pad the end of the URL with / if suffixSlash is true 12 func SanitizeUrl(url string, suffixSlash bool) string { 13 if len(url) == 0 { 14 return "" 15 } 16 strBuilder := strings.Builder{} 17 isAtForwardSlash := false 18 startLoc := 0 19 protocolRegExp, _ := regexp.Compile("https?://") 20 protocolMatch := protocolRegExp.FindAllString(url, 1) 21 if len(protocolMatch) > 0 { 22 startLoc += len(protocolMatch[0]) 23 strBuilder.WriteString(protocolMatch[0]) 24 } 25 26 for _, c := range url[startLoc:] { 27 if isAtForwardSlash && byte(c) == '/' { 28 continue 29 } 30 isAtForwardSlash = byte(c) == '/' 31 strBuilder.WriteByte(byte(c)) 32 } 33 34 sanitizedUrl := strBuilder.String() 35 if suffixSlash && sanitizedUrl[len(sanitizedUrl)-1] != '/' { 36 sanitizedUrl += "/" 37 } 38 39 if !suffixSlash && sanitizedUrl[len(sanitizedUrl)-1] == '/' { 40 sanitizedUrl = sanitizedUrl[:len(sanitizedUrl)-1] 41 } 42 43 return sanitizedUrl 44 }