compress.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. )
  10. /*
  11. * Default more not to gzip since gzip can be done on client side.
  12. */
  13. func IsGzippable(ext, mtype string) bool {
  14. if strings.HasPrefix(mtype, "text/") {
  15. return true
  16. }
  17. switch ext {
  18. case ".zip", ".rar", ".gz", ".bz2", ".xz":
  19. return false
  20. case ".pdf", ".txt", ".html", ".htm", ".css", ".js", ".json":
  21. return true
  22. }
  23. if strings.HasPrefix(mtype, "application/") {
  24. if strings.HasSuffix(mtype, "xml") {
  25. return true
  26. }
  27. if strings.HasSuffix(mtype, "script") {
  28. return true
  29. }
  30. }
  31. return false
  32. }
  33. func GzipData(input []byte) ([]byte, error) {
  34. buf := new(bytes.Buffer)
  35. w, _ := gzip.NewWriterLevel(buf, flate.BestCompression)
  36. if _, err := w.Write(input); err != nil {
  37. glog.V(2).Infoln("error compressing data:", err)
  38. return nil, err
  39. }
  40. if err := w.Close(); err != nil {
  41. glog.V(2).Infoln("error closing compressed data:", err)
  42. return nil, err
  43. }
  44. return buf.Bytes(), nil
  45. }
  46. func UnGzipData(input []byte) ([]byte, error) {
  47. buf := bytes.NewBuffer(input)
  48. r, _ := gzip.NewReader(buf)
  49. defer r.Close()
  50. output, err := ioutil.ReadAll(r)
  51. if err != nil {
  52. glog.V(2).Infoln("error uncompressing data:", err)
  53. }
  54. return output, err
  55. }