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.

103 lines
2.1 KiB

6 years ago
5 years ago
6 years ago
5 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. "golang.org/x/tools/godoc/util"
  9. "github.com/chrislusf/seaweedfs/weed/glog"
  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. */
  37. func IsGzippable(ext, mtype string, data []byte) bool {
  38. shouldBeZipped, iAmSure := IsGzippableFileType(ext, mtype)
  39. if iAmSure {
  40. return shouldBeZipped
  41. }
  42. isMostlyText := util.IsText(data)
  43. return isMostlyText
  44. }
  45. /*
  46. * Default more not to gzip since gzip can be done on client side.
  47. */func IsGzippableFileType(ext, mtype string) (shouldBeZipped, iAmSure bool) {
  48. // text
  49. if strings.HasPrefix(mtype, "text/") {
  50. return true, true
  51. }
  52. // images
  53. switch ext {
  54. case ".svg", ".bmp", ".wav":
  55. return true, true
  56. }
  57. if strings.HasPrefix(mtype, "image/") {
  58. return false, true
  59. }
  60. // by file name extension
  61. switch ext {
  62. case ".zip", ".rar", ".gz", ".bz2", ".xz":
  63. return false, true
  64. case ".pdf", ".txt", ".html", ".htm", ".css", ".js", ".json":
  65. return true, true
  66. case ".php", ".java", ".go", ".rb", ".c", ".cpp", ".h", ".hpp":
  67. return true, true
  68. case ".png", ".jpg", ".jpeg":
  69. return false, true
  70. }
  71. // by mime type
  72. if strings.HasPrefix(mtype, "application/") {
  73. if strings.HasSuffix(mtype, "xml") {
  74. return true, true
  75. }
  76. if strings.HasSuffix(mtype, "script") {
  77. return true, true
  78. }
  79. }
  80. if strings.HasPrefix(mtype, "audio/") {
  81. switch strings.TrimPrefix(mtype, "audio/") {
  82. case "wave", "wav", "x-wav", "x-pn-wav":
  83. return true, true
  84. }
  85. }
  86. return false, false
  87. }