gzip.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. gz.Reset(c.Writer)
  34. c.Header("Content-Encoding", "gzip")
  35. c.Header("Vary", "Accept-Encoding")
  36. c.Writer = &gzipWriter{c.Writer, gz}
  37. defer func() {
  38. gz.Close()
  39. c.Header("Content-Length", fmt.Sprint(c.Writer.Size()))
  40. }()
  41. c.Next()
  42. }
  43. }
  44. type gzipWriter struct {
  45. gin.ResponseWriter
  46. writer *gzip.Writer
  47. }
  48. func (g *gzipWriter) WriteString(s string) (int, error) {
  49. return g.writer.Write([]byte(s))
  50. }
  51. func (g *gzipWriter) Write(data []byte) (int, error) {
  52. return g.writer.Write(data)
  53. }
  54. // Fix: https://github.com/mholt/caddy/issues/38
  55. func (g *gzipWriter) WriteHeader(code int) {
  56. g.Header().Del("Content-Length")
  57. g.ResponseWriter.WriteHeader(code)
  58. }
  59. func shouldCompress(req *http.Request) bool {
  60. if !strings.Contains(req.Header.Get("Accept-Encoding"), "gzip") ||
  61. strings.Contains(req.Header.Get("Connection"), "Upgrade") ||
  62. strings.Contains(req.Header.Get("Content-Type"), "text/event-stream") {
  63. return false
  64. }
  65. extension := filepath.Ext(req.URL.Path)
  66. if len(extension) < 4 { // fast path
  67. return true
  68. }
  69. switch extension {
  70. case ".png", ".gif", ".jpeg", ".jpg":
  71. return false
  72. default:
  73. return true
  74. }
  75. }