2015-01-30 14:52:18 +08:00
|
|
|
// Package gzip provides a simple middleware layer that performs
|
|
|
|
// gzip compression on the response.
|
2015-01-30 13:04:18 +08:00
|
|
|
package gzip
|
|
|
|
|
|
|
|
import (
|
|
|
|
"compress/gzip"
|
|
|
|
"io"
|
|
|
|
"net/http"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/mholt/caddy/middleware"
|
|
|
|
)
|
|
|
|
|
|
|
|
// New creates a new gzip middleware instance.
|
|
|
|
func New(c middleware.Controller) (middleware.Middleware, error) {
|
|
|
|
return func(next http.HandlerFunc) http.HandlerFunc {
|
2015-01-30 13:46:09 +08:00
|
|
|
gz := Gzip{Next: next}
|
2015-01-30 13:04:18 +08:00
|
|
|
return gz.ServeHTTP
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Gzip is a http.Handler middleware type which gzips HTTP responses.
|
|
|
|
type Gzip struct {
|
2015-01-30 13:46:09 +08:00
|
|
|
Next http.HandlerFunc
|
2015-01-30 13:04:18 +08:00
|
|
|
// TODO: Compression level, other settings
|
|
|
|
}
|
|
|
|
|
|
|
|
// ServeHTTP serves a gzipped response if the client supports it.
|
2015-01-30 13:46:09 +08:00
|
|
|
func (g Gzip) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
2015-01-30 13:04:18 +08:00
|
|
|
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
|
2015-01-30 13:46:09 +08:00
|
|
|
g.Next(w, r)
|
2015-01-30 13:04:18 +08:00
|
|
|
return
|
|
|
|
}
|
|
|
|
w.Header().Set("Content-Encoding", "gzip")
|
|
|
|
gzipWriter := gzip.NewWriter(w)
|
|
|
|
defer gzipWriter.Close()
|
|
|
|
gz := gzipResponseWriter{Writer: gzipWriter, ResponseWriter: w}
|
2015-01-30 13:46:09 +08:00
|
|
|
g.Next(gz, r)
|
2015-01-30 13:04:18 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// gzipResponeWriter wraps the underlying Write method
|
|
|
|
// with a gzip.Writer to compress the output.
|
|
|
|
type gzipResponseWriter struct {
|
|
|
|
io.Writer
|
|
|
|
http.ResponseWriter
|
|
|
|
}
|
|
|
|
|
|
|
|
// Write wraps the underlying Write method to do compression.
|
|
|
|
func (w gzipResponseWriter) Write(b []byte) (int, error) {
|
|
|
|
if w.Header().Get("Content-Type") == "" {
|
|
|
|
w.Header().Set("Content-Type", http.DetectContentType(b))
|
|
|
|
}
|
|
|
|
n, err := w.Writer.Write(b)
|
|
|
|
return n, err
|
|
|
|
}
|