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.

57 lines
1.2 KiB

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