gzip.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Copyright 2019 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package rpc
  17. import (
  18. "compress/gzip"
  19. "io"
  20. "io/ioutil"
  21. "net/http"
  22. "strings"
  23. "sync"
  24. )
  25. var gzPool = sync.Pool{
  26. New: func() interface{} {
  27. w := gzip.NewWriter(ioutil.Discard)
  28. return w
  29. },
  30. }
  31. type gzipResponseWriter struct {
  32. io.Writer
  33. http.ResponseWriter
  34. }
  35. func (w *gzipResponseWriter) WriteHeader(status int) {
  36. w.Header().Del("Content-Length")
  37. w.ResponseWriter.WriteHeader(status)
  38. }
  39. func (w *gzipResponseWriter) Write(b []byte) (int, error) {
  40. return w.Writer.Write(b)
  41. }
  42. func newGzipHandler(next http.Handler) http.Handler {
  43. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  44. if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
  45. next.ServeHTTP(w, r)
  46. return
  47. }
  48. w.Header().Set("Content-Encoding", "gzip")
  49. gz := gzPool.Get().(*gzip.Writer)
  50. defer gzPool.Put(gz)
  51. gz.Reset(w)
  52. defer gz.Close()
  53. next.ServeHTTP(&gzipResponseWriter{ResponseWriter: w, Writer: gz}, r)
  54. })
  55. }