2022-06-09 15:05:27 +00:00
|
|
|
package utils
|
|
|
|
|
2022-06-23 09:04:37 +00:00
|
|
|
import (
|
2022-08-11 12:32:17 +00:00
|
|
|
"net/url"
|
2022-06-28 10:00:11 +00:00
|
|
|
stdpath "path"
|
2022-06-23 09:04:37 +00:00
|
|
|
"path/filepath"
|
2022-06-28 14:22:02 +00:00
|
|
|
"runtime"
|
2022-06-23 09:04:37 +00:00
|
|
|
"strings"
|
|
|
|
)
|
2022-06-09 15:05:27 +00:00
|
|
|
|
2022-06-23 09:04:37 +00:00
|
|
|
// StandardizePath convert path like '/' '/root' '/a/b'
|
|
|
|
func StandardizePath(path string) string {
|
2022-06-09 15:05:27 +00:00
|
|
|
path = strings.TrimSuffix(path, "/")
|
2022-06-27 12:56:17 +00:00
|
|
|
// abs path
|
2022-06-28 14:22:02 +00:00
|
|
|
if filepath.IsAbs(path) && runtime.GOOS == "windows" {
|
2022-06-23 09:04:37 +00:00
|
|
|
return path
|
|
|
|
}
|
|
|
|
// relative path with prefix '..'
|
2022-06-27 12:37:05 +00:00
|
|
|
if strings.HasPrefix(path, ".") {
|
2022-06-23 09:04:37 +00:00
|
|
|
return path
|
|
|
|
}
|
2022-06-09 15:05:27 +00:00
|
|
|
if !strings.HasPrefix(path, "/") {
|
|
|
|
path = "/" + path
|
|
|
|
}
|
|
|
|
return path
|
|
|
|
}
|
2022-06-11 06:43:03 +00:00
|
|
|
|
2022-06-13 06:53:44 +00:00
|
|
|
// PathEqual judge path is equal
|
2022-06-11 06:43:03 +00:00
|
|
|
func PathEqual(path1, path2 string) bool {
|
2022-06-23 09:04:37 +00:00
|
|
|
return StandardizePath(path1) == StandardizePath(path2)
|
2022-06-11 06:43:03 +00:00
|
|
|
}
|
2022-06-28 10:00:11 +00:00
|
|
|
|
|
|
|
func Ext(path string) string {
|
|
|
|
ext := stdpath.Ext(path)
|
|
|
|
if strings.HasPrefix(ext, ".") {
|
|
|
|
return ext[1:]
|
|
|
|
}
|
|
|
|
return ext
|
|
|
|
}
|
2022-08-11 12:32:17 +00:00
|
|
|
|
|
|
|
func EncodePath(path string, all ...bool) string {
|
|
|
|
seg := strings.Split(path, "/")
|
|
|
|
toReplace := []struct {
|
|
|
|
Src string
|
|
|
|
Dst string
|
|
|
|
}{
|
|
|
|
{Src: "%", Dst: "%25"},
|
|
|
|
{"%", "%25"},
|
|
|
|
{"?", "%3F"},
|
|
|
|
{"#", "%23"},
|
|
|
|
}
|
|
|
|
for i := range seg {
|
|
|
|
if len(all) > 0 && all[0] {
|
|
|
|
seg[i] = url.PathEscape(seg[i])
|
|
|
|
} else {
|
|
|
|
for j := range toReplace {
|
|
|
|
seg[i] = strings.ReplaceAll(seg[i], toReplace[j].Src, toReplace[j].Dst)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return strings.Join(seg, "/")
|
|
|
|
}
|