code.dwrz.net

Go monorepo.
Log | Files | Refs

util.go (1553B)


      1 package v4
      2 
      3 import (
      4 	"net/url"
      5 	"strings"
      6 )
      7 
      8 const doubleSpace = "  "
      9 
     10 // StripExcessSpaces will rewrite the passed in slice's string values to not
     11 // contain multiple side-by-side spaces.
     12 func StripExcessSpaces(str string) string {
     13 	var j, k, l, m, spaces int
     14 	// Trim trailing spaces
     15 	for j = len(str) - 1; j >= 0 && str[j] == ' '; j-- {
     16 	}
     17 
     18 	// Trim leading spaces
     19 	for k = 0; k < j && str[k] == ' '; k++ {
     20 	}
     21 	str = str[k : j+1]
     22 
     23 	// Strip multiple spaces.
     24 	j = strings.Index(str, doubleSpace)
     25 	if j < 0 {
     26 		return str
     27 	}
     28 
     29 	buf := []byte(str)
     30 	for k, m, l = j, j, len(buf); k < l; k++ {
     31 		if buf[k] == ' ' {
     32 			if spaces == 0 {
     33 				// First space.
     34 				buf[m] = buf[k]
     35 				m++
     36 			}
     37 			spaces++
     38 		} else {
     39 			// End of multiple spaces.
     40 			spaces = 0
     41 			buf[m] = buf[k]
     42 			m++
     43 		}
     44 	}
     45 
     46 	return string(buf[:m])
     47 }
     48 
     49 // GetURIPath returns the escaped URI component from the provided URL.
     50 func GetURIPath(u *url.URL) string {
     51 	var uriPath string
     52 
     53 	if len(u.Opaque) > 0 {
     54 		const schemeSep, pathSep, queryStart = "//", "/", "?"
     55 
     56 		opaque := u.Opaque
     57 		// Cut off the query string if present.
     58 		if idx := strings.Index(opaque, queryStart); idx >= 0 {
     59 			opaque = opaque[:idx]
     60 		}
     61 
     62 		// Cutout the scheme separator if present.
     63 		if strings.Index(opaque, schemeSep) == 0 {
     64 			opaque = opaque[len(schemeSep):]
     65 		}
     66 
     67 		// capture URI path starting with first path separator.
     68 		if idx := strings.Index(opaque, pathSep); idx >= 0 {
     69 			uriPath = opaque[idx:]
     70 		}
     71 	} else {
     72 		uriPath = u.EscapedPath()
     73 	}
     74 
     75 	if len(uriPath) == 0 {
     76 		uriPath = "/"
     77 	}
     78 
     79 	return uriPath
     80 }