MCPcopy Index your code
hub / github.com/labstack/echo / ToMiddleware

Method ToMiddleware

middleware/compress.go:69–145  ·  view source on GitHub ↗

ToMiddleware converts GzipConfig to middleware or returns an error for invalid configuration

()

Source from the content-addressed store, hash-verified

67
68// ToMiddleware converts GzipConfig to middleware or returns an error for invalid configuration
69func (config GzipConfig) ToMiddleware() (echo.MiddlewareFunc, error) {
70 if config.Skipper == nil {
71 config.Skipper = DefaultSkipper
72 }
73 if config.Level < -2 || config.Level > 9 { // these are consts: gzip.HuffmanOnly and gzip.BestCompression
74 return nil, errors.New("invalid gzip level")
75 }
76 if config.Level == 0 {
77 config.Level = -1
78 }
79 if config.MinLength < 0 {
80 config.MinLength = 0
81 }
82
83 pool := gzipCompressPool(config)
84 bpool := bufferPool()
85
86 return func(next echo.HandlerFunc) echo.HandlerFunc {
87 return func(c *echo.Context) error {
88 if config.Skipper(c) {
89 return next(c)
90 }
91
92 res := c.Response()
93 res.Header().Add(echo.HeaderVary, echo.HeaderAcceptEncoding)
94 if strings.Contains(c.Request().Header.Get(echo.HeaderAcceptEncoding), gzipScheme) {
95 i := pool.Get()
96 w, ok := i.(*gzip.Writer)
97 if !ok {
98 return echo.NewHTTPError(http.StatusInternalServerError, "invalid pool object")
99 }
100 rw := res
101 w.Reset(rw)
102 buf := bpool.Get().(*bytes.Buffer)
103 buf.Reset()
104
105 grw := &gzipResponseWriter{
106 Writer: w,
107 ResponseWriter: rw,
108 minLength: config.MinLength,
109 buffer: buf,
110 }
111 c.SetResponse(grw)
112 defer func() {
113 // There are different reasons for cases when we have not yet written response to the client and now need to do so.
114 // a) handler response had only response code and no response body (ala 404 or redirects etc). Response code need to be written now.
115 // b) body is shorter than our minimum length threshold and being buffered currently and needs to be written
116 if !grw.wroteBody {
117 if res.Header().Get(echo.HeaderContentEncoding) == gzipScheme {
118 res.Header().Del(echo.HeaderContentEncoding)
119 }
120 if grw.wroteHeader {
121 rw.WriteHeader(grw.code)
122 }
123 // We have to reset response to it's pristine state when
124 // nothing is written to body or error is returned.
125 // See issue #424, #407.
126 c.SetResponse(rw)

Callers

nothing calls this directly

Calls 11

gzipCompressPoolFunction · 0.85
bufferPoolFunction · 0.85
ResponseMethod · 0.80
RequestMethod · 0.80
SetResponseMethod · 0.80
AddMethod · 0.65
HeaderMethod · 0.45
GetMethod · 0.45
ResetMethod · 0.45
WriteHeaderMethod · 0.45
CloseMethod · 0.45

Tested by

no test coverage detected