file.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. func logn(n, b float64) float64 {
  25. return math.Log(n) / math.Log(b)
  26. }
  27. func humanateBytes(s uint64, base float64, sizes []string) string {
  28. if s < 10 {
  29. return fmt.Sprintf("%d B", s)
  30. }
  31. e := math.Floor(logn(float64(s), base))
  32. suffix := sizes[int(e)]
  33. val := float64(s) / math.Pow(base, math.Floor(e))
  34. f := "%.0f"
  35. if val < 10 {
  36. f = "%.1f"
  37. }
  38. return fmt.Sprintf(f+" %s", val, suffix)
  39. }
  40. // FileSize calculates the file size and generate user-friendly string.
  41. func FileSize(s int64) string {
  42. sizes := []string{"B", "KB", "MB", "GB", "TB", "PB", "EB"}
  43. return humanateBytes(uint64(s), 1024, sizes)
  44. }