gzip.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package gzip
  2. import (
  3. "compress/gzip"
  4. "fmt"
  5. "io/ioutil"
  6. "net/http"
  7. "path/filepath"
  8. "strings"
  9. "sync"
  10. "github.com/gin-gonic/gin"
  11. )
  12. const (
  13. BestCompression = gzip.BestCompression
  14. BestSpeed = gzip.BestSpeed
  15. DefaultCompression = gzip.DefaultCompression
  16. NoCompression = gzip.NoCompression
  17. )
  18. func Gzip(level int) gin.HandlerFunc {
  19. var gzPool sync.Pool
  20. gzPool.New = func() interface{} {
  21. gz, err := gzip.NewWriterLevel(ioutil.Discard, level)
  22. if err != nil {
  23. panic(err)
  24. }
  25. return gz
  26. }
  27. return func(c *gin.Context) {
  28. if !shouldCompress(c.Request) {
  29. return
  30. }
  31. gz := gzPool.Get().(*gzip.Writer)
  32. defer gzPool.Put(gz)
  33. defer gz.Reset(ioutil.Discard)
  34. gz.Reset(c.Writer)
  35. c.Header("Content-Encoding", "gzip")
  36. c.Header("Vary", "Accept-Encoding")
  37. c.Writer = &gzipWriter{c.Writer, gz}
  38. defer func() {
  39. gz.Close()
  40. c.Header("Content-Length", fmt.Sprint(c.Writer.Size()))
  41. }()
  42. c.Next()
  43. }
  44. }
  45. type gzipWriter struct {
  46. gin.ResponseWriter
  47. writer *gzip.Writer
  48. }
  49. func (g *gzipWriter) WriteString(s string) (int, error) {
  50. return g.writer.Write([]byte(s))
  51. }
  52. func (g *gzipWriter) Write(data []byte) (int, error) {
  53. return g.writer.Write(data)
  54. }
  55. // Fix: https://github.com/mholt/caddy/issues/38
  56. func (g *gzipWriter) WriteHeader(code int) {
  57. g.Header().Del("Content-Length")
  58. g.ResponseWriter.WriteHeader(code)
  59. }
  60. func shouldCompress(req *http.Request) bool {
  61. if !strings.Contains(req.Header.Get("Accept-Encoding"), "gzip") ||
  62. strings.Contains(req.Header.Get("Connection"), "Upgrade") ||
  63. strings.Contains(req.Header.Get("Content-Type"), "text/event-stream") {
  64. return false
  65. }
  66. extension := filepath.Ext(req.URL.Path)
  67. if len(extension) < 4 { // fast path
  68. return true
  69. }
  70. switch extension {
  71. case ".png", ".gif", ".jpeg", ".jpg":
  72. return false
  73. default:
  74. return true
  75. }
  76. }