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.

53 lines
901 B

  1. package util
  2. import (
  3. "compress/gzip"
  4. "fmt"
  5. "io"
  6. "sync"
  7. )
  8. var (
  9. gzipReaderPool = sync.Pool{
  10. New: func() interface{} {
  11. return new(gzip.Reader)
  12. //return gzip.NewReader()
  13. },
  14. }
  15. gzipWriterPool = sync.Pool{
  16. New: func() interface{} {
  17. w, _ := gzip.NewWriterLevel(nil, gzip.BestSpeed)
  18. return w
  19. },
  20. }
  21. )
  22. func GzipStream(w io.Writer, r io.Reader) (int64, error) {
  23. gw, ok := gzipWriterPool.Get().(*gzip.Writer)
  24. if !ok {
  25. return 0, fmt.Errorf("gzip: new writer error")
  26. }
  27. gw.Reset(w)
  28. defer func() {
  29. gw.Close()
  30. gzipWriterPool.Put(gw)
  31. }()
  32. return io.Copy(gw, r)
  33. }
  34. func GunzipStream(w io.Writer, r io.Reader) (int64, error) {
  35. gr, ok := gzipReaderPool.Get().(*gzip.Reader)
  36. if !ok {
  37. return 0, fmt.Errorf("gzip: new reader error")
  38. }
  39. if err := gr.Reset(r); err != nil {
  40. return 0, err
  41. }
  42. defer func() {
  43. gr.Close()
  44. gzipReaderPool.Put(gr)
  45. }()
  46. return io.Copy(w, gr)
  47. }