file.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package tool
  2. import (
  3. "fmt"
  4. "math"
  5. "net/http"
  6. "strings"
  7. )
  8. // IsTextFile returns true if file content format is plain text or empty.
  9. func IsTextFile(data []byte) bool {
  10. if len(data) == 0 {
  11. return true
  12. }
  13. return strings.Contains(http.DetectContentType(data), "text/")
  14. }
  15. func IsImageFile(data []byte) bool {
  16. return strings.Contains(http.DetectContentType(data), "image/")
  17. }
  18. func IsPDFFile(data []byte) bool {
  19. return strings.Contains(http.DetectContentType(data), "application/pdf")
  20. }
  21. func IsVideoFile(data []byte) bool {
  22. return strings.Contains(http.DetectContentType(data), "video/")
  23. }
  24. const (
  25. Byte = 1
  26. KByte = Byte * 1024
  27. MByte = KByte * 1024
  28. GByte = MByte * 1024
  29. TByte = GByte * 1024
  30. PByte = TByte * 1024
  31. EByte = PByte * 1024
  32. )
  33. var bytesSizeTable = map[string]uint64{
  34. "b": Byte,
  35. "kb": KByte,
  36. "mb": MByte,
  37. "gb": GByte,
  38. "tb": TByte,
  39. "pb": PByte,
  40. "eb": EByte,
  41. }
  42. func logn(n, b float64) float64 {
  43. return math.Log(n) / math.Log(b)
  44. }
  45. func humanateBytes(s uint64, base float64, sizes []string) string {
  46. if s < 10 {
  47. return fmt.Sprintf("%d B", s)
  48. }
  49. e := math.Floor(logn(float64(s), base))
  50. suffix := sizes[int(e)]
  51. val := float64(s) / math.Pow(base, math.Floor(e))
  52. f := "%.0f"
  53. if val < 10 {
  54. f = "%.1f"
  55. }
  56. return fmt.Sprintf(f+" %s", val, suffix)
  57. }
  58. // FileSize calculates the file size and generate user-friendly string.
  59. func FileSize(s int64) string {
  60. sizes := []string{"B", "KB", "MB", "GB", "TB", "PB", "EB"}
  61. return humanateBytes(uint64(s), 1024, sizes)
  62. }