You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

101 lines
2.1 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. package util
  2. import (
  3. "bytes"
  4. "compress/flate"
  5. "compress/gzip"
  6. "io/ioutil"
  7. "strings"
  8. "github.com/chrislusf/seaweedfs/weed/glog"
  9. "golang.org/x/tools/godoc/util"
  10. )
  11. func GzipData(input []byte) ([]byte, error) {
  12. buf := new(bytes.Buffer)
  13. w, _ := gzip.NewWriterLevel(buf, flate.BestSpeed)
  14. if _, err := w.Write(input); err != nil {
  15. glog.V(2).Infoln("error compressing data:", err)
  16. return nil, err
  17. }
  18. if err := w.Close(); err != nil {
  19. glog.V(2).Infoln("error closing compressed data:", err)
  20. return nil, err
  21. }
  22. return buf.Bytes(), nil
  23. }
  24. func UnGzipData(input []byte) ([]byte, error) {
  25. buf := bytes.NewBuffer(input)
  26. r, _ := gzip.NewReader(buf)
  27. defer r.Close()
  28. output, err := ioutil.ReadAll(r)
  29. if err != nil {
  30. glog.V(2).Infoln("error uncompressing data:", err)
  31. }
  32. return output, err
  33. }
  34. /*
  35. * Default more not to gzip since gzip can be done on client side.
  36. */func IsGzippable(ext, mtype string, data []byte) bool {
  37. shouldBeZipped, iAmSure := IsGzippableFileType(ext, mtype)
  38. if iAmSure {
  39. return shouldBeZipped
  40. }
  41. isMostlyText := util.IsText(data)
  42. return isMostlyText
  43. }
  44. /*
  45. * Default more not to gzip since gzip can be done on client side.
  46. */func IsGzippableFileType(ext, mtype string) (shouldBeZipped, iAmSure bool) {
  47. // text
  48. if strings.HasPrefix(mtype, "text/") {
  49. return true, true
  50. }
  51. // images
  52. switch ext {
  53. case ".svg", ".bmp", ".wav":
  54. return true, true
  55. }
  56. if strings.HasPrefix(mtype, "image/") {
  57. return false, true
  58. }
  59. // by file name extension
  60. switch ext {
  61. case ".zip", ".rar", ".gz", ".bz2", ".xz":
  62. return false, true
  63. case ".pdf", ".txt", ".html", ".htm", ".css", ".js", ".json":
  64. return true, true
  65. case ".php", ".java", ".go", ".rb", ".c", ".cpp", ".h", ".hpp":
  66. return true, true
  67. case ".png", ".jpg", ".jpeg":
  68. return false, true
  69. }
  70. // by mime type
  71. if strings.HasPrefix(mtype, "application/") {
  72. if strings.HasSuffix(mtype, "xml") {
  73. return true, true
  74. }
  75. if strings.HasSuffix(mtype, "script") {
  76. return true, true
  77. }
  78. }
  79. if strings.HasPrefix(mtype, "audio/") {
  80. switch strings.TrimPrefix(mtype, "audio/") {
  81. case "wave", "wav", "x-wav", "x-pn-wav":
  82. return true, true
  83. }
  84. }
  85. return false, false
  86. }