github.com/gofiber/fiber/v2@v2.47.0/utils/convert.go (about) 1 // ⚡️ Fiber is an Express inspired web framework written in Go with ☕️ 2 // 🤖 Github Repository: https://github.com/gofiber/fiber 3 // 📌 API Documentation: https://docs.gofiber.io 4 5 package utils 6 7 import ( 8 "fmt" 9 "reflect" 10 "strconv" 11 "strings" 12 "time" 13 ) 14 15 // CopyString copies a string to make it immutable 16 func CopyString(s string) string { 17 return string(UnsafeBytes(s)) 18 } 19 20 // CopyBytes copies a slice to make it immutable 21 func CopyBytes(b []byte) []byte { 22 tmp := make([]byte, len(b)) 23 copy(tmp, b) 24 return tmp 25 } 26 27 const ( 28 uByte = 1 << (10 * iota) // 1 << 10 == 1024 29 uKilobyte 30 uMegabyte 31 uGigabyte 32 uTerabyte 33 uPetabyte 34 uExabyte 35 ) 36 37 // ByteSize returns a human-readable byte string of the form 10M, 12.5K, and so forth. 38 // The unit that results in the smallest number greater than or equal to 1 is always chosen. 39 func ByteSize(bytes uint64) string { 40 unit := "" 41 value := float64(bytes) 42 switch { 43 case bytes >= uExabyte: 44 unit = "EB" 45 value /= uExabyte 46 case bytes >= uPetabyte: 47 unit = "PB" 48 value /= uPetabyte 49 case bytes >= uTerabyte: 50 unit = "TB" 51 value /= uTerabyte 52 case bytes >= uGigabyte: 53 unit = "GB" 54 value /= uGigabyte 55 case bytes >= uMegabyte: 56 unit = "MB" 57 value /= uMegabyte 58 case bytes >= uKilobyte: 59 unit = "KB" 60 value /= uKilobyte 61 case bytes >= uByte: 62 unit = "B" 63 default: 64 return "0B" 65 } 66 result := strconv.FormatFloat(value, 'f', 1, 64) 67 result = strings.TrimSuffix(result, ".0") 68 return result + unit 69 } 70 71 // ToString Change arg to string 72 func ToString(arg interface{}, timeFormat ...string) string { 73 tmp := reflect.Indirect(reflect.ValueOf(arg)).Interface() 74 switch v := tmp.(type) { 75 case int: 76 return strconv.Itoa(v) 77 case int8: 78 return strconv.FormatInt(int64(v), 10) 79 case int16: 80 return strconv.FormatInt(int64(v), 10) 81 case int32: 82 return strconv.FormatInt(int64(v), 10) 83 case int64: 84 return strconv.FormatInt(v, 10) 85 case uint: 86 return strconv.Itoa(int(v)) 87 case uint8: 88 return strconv.FormatInt(int64(v), 10) 89 case uint16: 90 return strconv.FormatInt(int64(v), 10) 91 case uint32: 92 return strconv.FormatInt(int64(v), 10) 93 case uint64: 94 return strconv.FormatInt(int64(v), 10) 95 case string: 96 return v 97 case []byte: 98 return string(v) 99 case bool: 100 return strconv.FormatBool(v) 101 case float32: 102 return strconv.FormatFloat(float64(v), 'f', -1, 32) 103 case float64: 104 return strconv.FormatFloat(v, 'f', -1, 64) 105 case time.Time: 106 if len(timeFormat) > 0 { 107 return v.Format(timeFormat[0]) 108 } 109 return v.Format("2006-01-02 15:04:05") 110 case reflect.Value: 111 return ToString(v.Interface(), timeFormat...) 112 case fmt.Stringer: 113 return v.String() 114 default: 115 return "" 116 } 117 }