Commit 80ef5d76 authored by Matthew Holt's avatar Matthew Holt

Moved gzip middleware into its own package

Trying a different format where the middleware is a type that satisfies http.Handler
parent affd4708
package middleware
package gzip
import (
"compress/gzip"
"io"
"net/http"
"strings"
"github.com/mholt/caddy/middleware"
)
func Gzip(p parser) Middleware {
// New creates a new gzip middleware instance.
func New(c middleware.Controller) (middleware.Middleware, error) {
return func(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
gz := Gzip{next: next}
return gz.ServeHTTP
}, nil
}
// Gzip is a http.Handler middleware type which gzips HTTP responses.
type Gzip struct {
next http.HandlerFunc
// TODO: Compression level, other settings
}
// ServeHTTP serves a gzipped response if the client supports it.
func (g *Gzip) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
next(w, r)
g.next(w, r)
return
}
w.Header().Set("Content-Encoding", "gzip")
gzipWriter := gzip.NewWriter(w)
defer gzipWriter.Close()
gz := gzipResponseWriter{Writer: gzipWriter, ResponseWriter: w}
next(gz, r)
}
}
g.next(gz, r)
}
// gzipResponeWriter wraps the underlying Write method
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment