tools.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. package tools
  2. import (
  3. "bufio"
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "math/rand"
  8. "os"
  9. "os/exec"
  10. "path"
  11. "path/filepath"
  12. "reflect"
  13. "runtime"
  14. "sort"
  15. "strconv"
  16. "strings"
  17. "time"
  18. )
  19. // 获取结构中的Name标签
  20. // 返回字典
  21. func StructTagNameMap(str interface{}, tag string) (ret map[string]string) {
  22. ret = make(map[string]string)
  23. s := reflect.TypeOf(str).Elem()
  24. for i := 0; i < s.NumField(); i++ {
  25. if s.Field(i).Tag.Get(tag) != "" {
  26. ret[s.Field(i).Name] = s.Field(i).Tag.Get(tag) //将tag输出
  27. }
  28. }
  29. return
  30. }
  31. // 获取结构中的Name标签
  32. // 返回数组
  33. // Tag中为-号,则不显示
  34. func StructTagNameGroup(str interface{}, tag string) (ret []string) {
  35. s := reflect.TypeOf(str).Elem()
  36. for i := 0; i < s.NumField(); i++ {
  37. if s.Field(i).Tag.Get(tag) != "-" {
  38. ret = append(ret, s.Field(i).Name) //将tag输出
  39. }
  40. }
  41. return
  42. }
  43. // 判断文件或文件夹是否存在
  44. func IsExist(path string) bool {
  45. _, err := os.Stat(path)
  46. if err != nil {
  47. if os.IsExist(err) {
  48. return true
  49. }
  50. if os.IsNotExist(err) {
  51. return false
  52. }
  53. fmt.Println(err)
  54. return false
  55. }
  56. return true
  57. }
  58. // 调试信息输出
  59. func Debug(show bool, args ...interface{}) {
  60. if show { // 调试信息可以通过全局变量,统一关闭
  61. fmt.Println(args...)
  62. }
  63. }
  64. // 随机数
  65. func RndNum(max int) int {
  66. rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
  67. return rnd.Intn(100)
  68. }
  69. // 生成几位随机数的字符串
  70. func RandString(len int) string {
  71. r := rand.New(rand.NewSource(time.Now().UnixNano()))
  72. bytes := make([]byte, len)
  73. for i := 0; i < len; i++ {
  74. b := r.Intn(10) + 48
  75. bytes[i] = byte(b)
  76. }
  77. return string(bytes)
  78. }
  79. // 生成重复字符
  80. func Repeat(str string, num int) (ret string) {
  81. for i := 0; i < num; i++ {
  82. ret = ret + str
  83. }
  84. return
  85. }
  86. // 转换 --------------------------------------
  87. func StrToInt(str string) int {
  88. i, e := strconv.Atoi(str)
  89. if e != nil {
  90. return 0
  91. }
  92. return i
  93. }
  94. func StrToUInt(str string) uint {
  95. i, e := strconv.Atoi(str)
  96. if e != nil {
  97. return 0
  98. }
  99. return uint(i)
  100. }
  101. func UintToInt64(num uint) int64 {
  102. return int64(num)
  103. }
  104. // 对Int数取绝对值
  105. func AbsByInt(num int) int {
  106. if num < 0 {
  107. return -num
  108. }
  109. return num
  110. }
  111. // 数值转字符
  112. func IntToStr(num int) string {
  113. return strconv.Itoa(num)
  114. }
  115. // interface 转字符
  116. func InterfaceToStr(value interface{}) string {
  117. if str, ok := value.(string); ok {
  118. return str
  119. }
  120. return ""
  121. }
  122. // 字符串数组包含判断
  123. func StringIn(target string, str_array []string) bool {
  124. sort.Strings(str_array)
  125. index := sort.SearchStrings(str_array, target)
  126. if index < len(str_array) && str_array[index] == target {
  127. return true
  128. }
  129. return false
  130. }
  131. // 随机字串
  132. func RndNonceStr() string {
  133. str := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  134. bytes := []byte(str)
  135. result := []byte{}
  136. r := rand.New(rand.NewSource(time.Now().UnixNano()))
  137. for i := 0; i < 32; i++ {
  138. result = append(result, bytes[r.Intn(len(bytes))])
  139. }
  140. return string(result)
  141. }
  142. // 执行命令
  143. func Command(params []string) (string, error) {
  144. var c *exec.Cmd
  145. switch runtime.GOOS {
  146. case "darwin":
  147. case "windows":
  148. para := append([]string{"/C"}, params[0:]...)
  149. c = exec.Command("cmd", para...)
  150. case "linux":
  151. para := append([]string{"-c"}, params[0:]...)
  152. c = exec.Command("bash", para...)
  153. }
  154. output, err := c.CombinedOutput()
  155. return string(output), err
  156. }
  157. // 获取所有文件
  158. func AllFileByName(pathSeparator string, fileDir string, extFile string, hasDir bool) (ret []string) {
  159. files, _ := ioutil.ReadDir(fileDir)
  160. for _, onefile := range files {
  161. if onefile.IsDir() {
  162. // fmt.Println(onefile.Name())
  163. //fmt.Println(tmpPrefix, onefile.Name(), "目录:")
  164. if hasDir {
  165. AllFileByName(pathSeparator, fileDir+pathSeparator+onefile.Name(), extFile, hasDir)
  166. }
  167. } else {
  168. if strings.ToUpper(extFile) == strings.ToUpper(path.Ext(onefile.Name())) || extFile == "" {
  169. ret = append(ret, onefile.Name())
  170. }
  171. }
  172. }
  173. return
  174. }
  175. // 删除文件
  176. func RemoveFile(path string, fileList []string) {
  177. for _, n := range fileList {
  178. os.Remove(path + n)
  179. }
  180. }
  181. // 复制文件
  182. func CopyFile(srcFilePath string, dstFilePath string) (written int64, err error) {
  183. srcFile, err := os.Open(srcFilePath)
  184. if err != nil {
  185. fmt.Printf("打开源文件错误,错误信息=%v\n", err)
  186. }
  187. defer srcFile.Close()
  188. reader := bufio.NewReader(srcFile)
  189. dstFile, err := os.OpenFile(dstFilePath, os.O_WRONLY|os.O_CREATE, 0777)
  190. if err != nil {
  191. fmt.Printf("打开目标文件错误,错误信息=%v\n", err)
  192. return
  193. }
  194. writer := bufio.NewWriter(dstFile)
  195. defer dstFile.Close()
  196. return io.Copy(writer, reader)
  197. }
  198. // 获取当前程序名
  199. func GetMeName() string {
  200. return filepath.Base(os.Args[0])
  201. }
  202. // 获取字符长度
  203. // GetStrLength("这是中文,和ABC长度.😂")
  204. // 返回:表情符数量,汉字数量,英文数量
  205. func GetStrLength(str string) (mNum int, cNum int, eNum int) {
  206. rs := []rune(str)
  207. for i := 0; i < len(rs); i++ {
  208. switch len(string(rs[i])) {
  209. case 4:
  210. mNum += 1
  211. case 3:
  212. cNum += 1
  213. case 1:
  214. eNum += 1
  215. }
  216. }
  217. return mNum, cNum, eNum // 表情符数量,汉字数量,英文数量
  218. }
  219. // 支持三元表达 -------------------------------------------------
  220. // callFn if args[i] == func, run it
  221. func callFn(f interface{}) interface{} {
  222. if f != nil {
  223. t := reflect.TypeOf(f)
  224. if t.Kind() == reflect.Func && t.NumIn() == 0 {
  225. function := reflect.ValueOf(f)
  226. in := make([]reflect.Value, 0)
  227. out := function.Call(in)
  228. if num := len(out); num > 0 {
  229. list := make([]interface{}, num)
  230. for i, value := range out {
  231. list[i] = value.Interface()
  232. }
  233. if num == 1 {
  234. return list[0]
  235. }
  236. return list
  237. }
  238. return nil
  239. }
  240. }
  241. return f
  242. }
  243. func isZero(f interface{}) bool {
  244. v := reflect.ValueOf(f)
  245. switch v.Kind() {
  246. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  247. return v.Int() == 0
  248. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  249. return v.Uint() == 0
  250. case reflect.Float32, reflect.Float64:
  251. return v.Float() == 0
  252. case reflect.String:
  253. str := v.String()
  254. if str == "" {
  255. return true
  256. }
  257. zero, error := strconv.ParseFloat(str, 10)
  258. if zero == 0 && error == nil {
  259. return true
  260. }
  261. boolean, error := strconv.ParseBool(str)
  262. return boolean == false && error == nil
  263. default:
  264. return false
  265. }
  266. }
  267. // If - (a ? b : c) Or (a && b)
  268. // var a = If(20 > 50, true, false) // a = false
  269. // var b = Or(a, 100) // b = 100
  270. // var c = If(b, 50) // c = 50
  271. // var fn = If(c > 40, func(){ return "ok" }) // fn = "ok"
  272. func If(args ...interface{}) interface{} {
  273. var condition = callFn(args[0])
  274. if len(args) == 1 {
  275. return condition
  276. }
  277. var trueVal = args[1]
  278. var falseVal interface{}
  279. if len(args) > 2 {
  280. falseVal = args[2]
  281. } else {
  282. falseVal = nil
  283. }
  284. if condition == nil {
  285. return callFn(falseVal)
  286. } else if v, ok := condition.(bool); ok {
  287. if v == false {
  288. return callFn(falseVal)
  289. }
  290. } else if isZero(condition) {
  291. return callFn(falseVal)
  292. } else if v, ok := condition.(error); ok {
  293. if v != nil {
  294. fmt.Println(v)
  295. return condition
  296. }
  297. }
  298. return callFn(trueVal)
  299. }
  300. // Or - (a || b)
  301. func Or(args ...interface{}) interface{} {
  302. var condition = callFn(args[0])
  303. if len(args) == 1 {
  304. return condition
  305. }
  306. if condition == nil {
  307. return callFn(args[1])
  308. }
  309. if v, ok := condition.(bool); ok {
  310. if v == false {
  311. return callFn(args[1])
  312. }
  313. } else if isZero(condition) {
  314. return callFn(args[1])
  315. } else if v, ok := condition.(error); ok {
  316. if v != nil {
  317. fmt.Println(v)
  318. return condition
  319. }
  320. }
  321. return condition
  322. }
  323. // 将字符填满位数 str 要填充的字符 size 填充为多少位 addStr 填充什么字符
  324. func StrSetSize(str string, size int, addStr string) string {
  325. var a string
  326. if len(str) > size {
  327. return str[0:size]
  328. } else {
  329. for i := 0; i < size-len(str); i++ {
  330. a = a + addStr
  331. }
  332. return fmt.Sprintf("%s%s", str, a)
  333. }
  334. }