github.com/cnotch/ipchub@v1.1.0/utils/path.go (about)

     1  // Copyright (c) 2019,CAOHONGJU 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 utils
     6  
     7  import (
     8  	"path"
     9  	"strings"
    10  )
    11  
    12  // CanonicalPath 获取合法的path
    13  func CanonicalPath(p string) string {
    14  	p = strings.ToLower(strings.TrimSpace(p))
    15  
    16  	if p == "" {
    17  		return "/"
    18  	}
    19  
    20  	if p[0] != '/' {
    21  		p = "/" + p
    22  	}
    23  
    24  	np := path.Clean(p)
    25  	// path.Clean removes trailing slash except for root;
    26  	// put the trailing slash back if necessary.
    27  	if p[len(p)-1] == '/' && np != "/" {
    28  		// Fast path for common case of p being the string we want:
    29  		if len(p) == len(np)+1 && strings.HasPrefix(p, np) {
    30  			np = p
    31  		} else {
    32  			np += "/"
    33  		}
    34  	}
    35  
    36  	return np
    37  }