github.com/iikira/iikira-go-utils@v0.0.0-20230610031953-f2cb11cde33a/utils/utils.go (about) 1 // Package pcsutil 工具包 2 package utils 3 4 import ( 5 "compress/gzip" 6 "flag" 7 "io" 8 "io/ioutil" 9 "net/http/cookiejar" 10 "net/url" 11 "strings" 12 ) 13 14 // TrimPathPrefix 去除目录的前缀 15 func TrimPathPrefix(path, prefixPath string) string { 16 if prefixPath == "/" { 17 return path 18 } 19 return strings.TrimPrefix(path, prefixPath) 20 } 21 22 // ContainsString 检测字符串是否在字符串数组里 23 func ContainsString(ss []string, s string) bool { 24 for k := range ss { 25 if ss[k] == s { 26 return true 27 } 28 } 29 return false 30 } 31 32 // GetURLCookieString 返回cookie字串 33 func GetURLCookieString(urlString string, jar *cookiejar.Jar) string { 34 u, _ := url.Parse(urlString) 35 cookies := jar.Cookies(u) 36 cookieString := "" 37 for _, v := range cookies { 38 cookieString += v.String() + "; " 39 } 40 cookieString = strings.TrimRight(cookieString, "; ") 41 return cookieString 42 } 43 44 // DecompressGZIP 对 io.Reader 数据, 进行 gzip 解压 45 func DecompressGZIP(r io.Reader) ([]byte, error) { 46 gzipReader, err := gzip.NewReader(r) 47 if err != nil { 48 return nil, err 49 } 50 gzipReader.Close() 51 return ioutil.ReadAll(gzipReader) 52 } 53 54 // FlagProvided 检测命令行是否提供名为 name 的 flag, 支持多个name(names) 55 func FlagProvided(names ...string) bool { 56 if len(names) == 0 { 57 return false 58 } 59 var targetFlag *flag.Flag 60 for _, name := range names { 61 targetFlag = flag.Lookup(name) 62 if targetFlag == nil { 63 return false 64 } 65 if targetFlag.DefValue == targetFlag.Value.String() { 66 return false 67 } 68 } 69 return true 70 } 71 72 // Trigger 用于触发事件 73 func Trigger(f func()) { 74 if f == nil { 75 return 76 } 77 go f() 78 } 79 80 // TriggerOnSync 用于触发事件, 同步触发 81 func TriggerOnSync(f func()) { 82 if f == nil { 83 return 84 } 85 f() 86 }