Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

gzip.go 3.4 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
  1. // Copyright 2013 Martini Authors
  2. // Copyright 2015 The Macaron Authors
  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 gzip
  16. import (
  17. "bufio"
  18. "fmt"
  19. "net"
  20. "net/http"
  21. "strings"
  22. "github.com/klauspost/compress/gzip"
  23. "gopkg.in/macaron.v1"
  24. )
  25. const (
  26. _HEADER_ACCEPT_ENCODING = "Accept-Encoding"
  27. _HEADER_CONTENT_ENCODING = "Content-Encoding"
  28. _HEADER_CONTENT_TYPE = "Content-Type"
  29. _HEADER_VARY = "Vary"
  30. )
  31. // Options represents a struct for specifying configuration options for the GZip middleware.
  32. type Options struct {
  33. // Compression level. Can be DefaultCompression(-1), ConstantCompression(-2)
  34. // or any integer value between BestSpeed(1) and BestCompression(9) inclusive.
  35. CompressionLevel int
  36. }
  37. func isCompressionLevelValid(level int) bool {
  38. return level == gzip.DefaultCompression ||
  39. level == gzip.ConstantCompression ||
  40. (level >= gzip.BestSpeed && level <= gzip.BestCompression)
  41. }
  42. func prepareOptions(options []Options) Options {
  43. var opt Options
  44. if len(options) > 0 {
  45. opt = options[0]
  46. }
  47. if !isCompressionLevelValid(opt.CompressionLevel) {
  48. // For web content, level 4 seems to be a sweet spot.
  49. opt.CompressionLevel = 4
  50. }
  51. return opt
  52. }
  53. // Gziper returns a Handler that adds gzip compression to all requests.
  54. // Make sure to include the Gzip middleware above other middleware
  55. // that alter the response body (like the render middleware).
  56. func Gziper(options ...Options) macaron.Handler {
  57. opt := prepareOptions(options)
  58. return func(ctx *macaron.Context) {
  59. if !strings.Contains(ctx.Req.Header.Get(_HEADER_ACCEPT_ENCODING), "gzip") {
  60. return
  61. }
  62. headers := ctx.Resp.Header()
  63. headers.Set(_HEADER_CONTENT_ENCODING, "gzip")
  64. headers.Set(_HEADER_VARY, _HEADER_ACCEPT_ENCODING)
  65. // We've made sure compression level is valid in prepareGzipOptions,
  66. // no need to check same error again.
  67. gz, err := gzip.NewWriterLevel(ctx.Resp, opt.CompressionLevel)
  68. if err != nil {
  69. panic(err.Error())
  70. }
  71. defer gz.Close()
  72. gzw := gzipResponseWriter{gz, ctx.Resp}
  73. ctx.Resp = gzw
  74. ctx.MapTo(gzw, (*http.ResponseWriter)(nil))
  75. // Check if render middleware has been registered,
  76. // if yes, we need to modify ResponseWriter for it as well.
  77. if _, ok := ctx.Render.(*macaron.DummyRender); !ok {
  78. ctx.Render.SetResponseWriter(gzw)
  79. }
  80. ctx.Next()
  81. // delete content length after we know we have been written to
  82. gzw.Header().Del("Content-Length")
  83. }
  84. }
  85. type gzipResponseWriter struct {
  86. w *gzip.Writer
  87. macaron.ResponseWriter
  88. }
  89. func (grw gzipResponseWriter) Write(p []byte) (int, error) {
  90. if len(grw.Header().Get(_HEADER_CONTENT_TYPE)) == 0 {
  91. grw.Header().Set(_HEADER_CONTENT_TYPE, http.DetectContentType(p))
  92. }
  93. return grw.w.Write(p)
  94. }
  95. func (grw gzipResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
  96. hijacker, ok := grw.ResponseWriter.(http.Hijacker)
  97. if !ok {
  98. return nil, nil, fmt.Errorf("the ResponseWriter doesn't support the Hijacker interface")
  99. }
  100. return hijacker.Hijack()
  101. }
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...