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.

95 lines
2.0 KiB

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