utils.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package main
  2. import (
  3. "fmt"
  4. "strconv"
  5. "strings"
  6. )
  7. func inSlice(str string, l []string) bool {
  8. for i := range l {
  9. if l[i] == str {
  10. return true
  11. }
  12. }
  13. return false
  14. }
  15. func toRealType(str string) interface{} {
  16. if i, err := isint(str); err == nil {
  17. return i
  18. }
  19. if b, err := isbool(str); err == nil {
  20. return b
  21. }
  22. if f, err := isfloat(str); err == nil {
  23. return f
  24. }
  25. if strings.HasPrefix(str, "[") && strings.HasSuffix(str, "]") {
  26. bstr := []byte(str)
  27. strs := strings.Split(string(bstr[1:len(bstr)-1]), ",")
  28. var r []interface{}
  29. for _, s := range strs {
  30. if i, err := isint(s); err == nil {
  31. r = append(r, i)
  32. continue
  33. }
  34. if i, err := isbool(s); err == nil {
  35. r = append(r, i)
  36. continue
  37. }
  38. if i, err := isfloat(s); err == nil {
  39. r = append(r, i)
  40. continue
  41. }
  42. r = append(r, strings.Trim(s, "\"' "))
  43. }
  44. return r
  45. }
  46. return str
  47. }
  48. func isint(v string) (i int, err error) {
  49. return strconv.Atoi(v)
  50. }
  51. func isbool(v string) (bool, error) {
  52. return strconv.ParseBool(v)
  53. }
  54. func isfloat(v string) (float64, error) {
  55. return strconv.ParseFloat(v, 64)
  56. }
  57. // Convert bytes to human readable string. Like a 2 MB, 64.2 KB, 52 B
  58. func FormatBytes(i int64) (result string) {
  59. switch {
  60. case i > (1024 * 1024 * 1024 * 1024):
  61. result = fmt.Sprintf("%#.02f TB", float64(i)/1024/1024/1024/1024)
  62. case i > (1024 * 1024 * 1024):
  63. result = fmt.Sprintf("%#.02f GB", float64(i)/1024/1024/1024)
  64. case i > (1024 * 1024):
  65. result = fmt.Sprintf("%#.02f MB", float64(i)/1024/1024)
  66. case i > 1024:
  67. result = fmt.Sprintf("%#.02f KB", float64(i)/1024)
  68. default:
  69. result = fmt.Sprintf("%d B", i)
  70. }
  71. result = strings.Trim(result, " ")
  72. return
  73. }