gzip.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // Copyright 2013 Martini Authors
  2. // Copyright 2014 Unknwon
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License"): you may
  5. // not use this file except in compliance with the License. You may obtain
  6. // a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. // License for the specific language governing permissions and limitations
  14. // under the License.
  15. package macaron
  16. import (
  17. "bufio"
  18. "compress/gzip"
  19. "fmt"
  20. "net"
  21. "net/http"
  22. "strings"
  23. )
  24. const (
  25. HeaderAcceptEncoding = "Accept-Encoding"
  26. HeaderContentEncoding = "Content-Encoding"
  27. HeaderContentLength = "Content-Length"
  28. HeaderContentType = "Content-Type"
  29. HeaderVary = "Vary"
  30. )
  31. // Gziper returns a Handler that adds gzip compression to all requests.
  32. // Make sure to include the Gzip middleware above other middleware
  33. // that alter the response body (like the render middleware).
  34. func Gziper() Handler {
  35. return func(ctx *Context) {
  36. if !strings.Contains(ctx.Req.Header.Get(HeaderAcceptEncoding), "gzip") {
  37. return
  38. }
  39. headers := ctx.Resp.Header()
  40. headers.Set(HeaderContentEncoding, "gzip")
  41. headers.Set(HeaderVary, HeaderAcceptEncoding)
  42. gz := gzip.NewWriter(ctx.Resp)
  43. defer gz.Close()
  44. gzw := gzipResponseWriter{gz, ctx.Resp}
  45. ctx.Resp = gzw
  46. ctx.MapTo(gzw, (*http.ResponseWriter)(nil))
  47. ctx.Next()
  48. // delete content length after we know we have been written to
  49. gzw.Header().Del("Content-Length")
  50. }
  51. }
  52. type gzipResponseWriter struct {
  53. w *gzip.Writer
  54. ResponseWriter
  55. }
  56. func (grw gzipResponseWriter) Write(p []byte) (int, error) {
  57. if len(grw.Header().Get(HeaderContentType)) == 0 {
  58. grw.Header().Set(HeaderContentType, http.DetectContentType(p))
  59. }
  60. return grw.w.Write(p)
  61. }
  62. func (grw gzipResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
  63. hijacker, ok := grw.ResponseWriter.(http.Hijacker)
  64. if !ok {
  65. return nil, nil, fmt.Errorf("the ResponseWriter doesn't support the Hijacker interface")
  66. }
  67. return hijacker.Hijack()
  68. }