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.

82 lines
1.7 KiB

  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. // text
  16. if strings.HasPrefix(mtype, "text/") {
  17. return true
  18. }
  19. // images
  20. switch ext {
  21. case ".svg", ".bmp":
  22. return true
  23. }
  24. if strings.HasPrefix(mtype, "image/") {
  25. return false
  26. }
  27. // by file name extention
  28. switch ext {
  29. case ".zip", ".rar", ".gz", ".bz2", ".xz":
  30. return false
  31. case ".pdf", ".txt", ".html", ".htm", ".css", ".js", ".json":
  32. return true
  33. case ".php", ".java", ".go", ".rb", ".c", ".cpp", ".h", ".hpp":
  34. return true
  35. case ".png", ".jpg", ".jpeg":
  36. return false
  37. }
  38. // by mime type
  39. if strings.HasPrefix(mtype, "application/") {
  40. if strings.HasSuffix(mtype, "xml") {
  41. return true
  42. }
  43. if strings.HasSuffix(mtype, "script") {
  44. return true
  45. }
  46. }
  47. isMostlyText := util.IsText(data)
  48. return isMostlyText
  49. }
  50. func GzipData(input []byte) ([]byte, error) {
  51. buf := new(bytes.Buffer)
  52. w, _ := gzip.NewWriterLevel(buf, flate.BestCompression)
  53. if _, err := w.Write(input); err != nil {
  54. glog.V(2).Infoln("error compressing data:", err)
  55. return nil, err
  56. }
  57. if err := w.Close(); err != nil {
  58. glog.V(2).Infoln("error closing compressed data:", err)
  59. return nil, err
  60. }
  61. return buf.Bytes(), nil
  62. }
  63. func UnGzipData(input []byte) ([]byte, error) {
  64. buf := bytes.NewBuffer(input)
  65. r, _ := gzip.NewReader(buf)
  66. defer r.Close()
  67. output, err := ioutil.ReadAll(r)
  68. if err != nil {
  69. glog.V(2).Infoln("error uncompressing data:", err)
  70. }
  71. return output, err
  72. }