Пример #1
0
func Gzip(ctx *stack.Context, next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		if !strings.Contains(req.Header.Get("Accept-Encoding"), "gzip") ||
			ctx.Get("handled").(bool) == true {
			// move on to next handler in the chain
			next.ServeHTTP(w, req)
			return
		}
		w.Header().Set("Content-Encoding", "gzip")
		gz := gzip.NewWriter(w)
		defer gz.Close()
		gzw := gzipResponseWriter{Writer: gz, ResponseWriter: w}
		ctx.Put("handled", true)
		defer ctx.Delete("handled")
		next.ServeHTTP(gzw, req)
	})
}
Пример #2
0
func Deflate(ctx *stack.Context, next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		if !strings.Contains(req.Header.Get("Accept-Encoding"), "deflate") ||
			ctx.Get("handled").(bool) == true {
			next.ServeHTTP(w, req)
			return
		}
		fl, err := flate.NewWriter(w, -1) // Use default compression level
		if err != nil {
			next.ServeHTTP(w, req)
			return
		}
		w.Header().Set("Content-Encoding", "deflate")
		defer fl.Close()
		flw := flateResponseWriter{Writer: fl, ResponseWriter: w}
		ctx.Put("handled", true)
		defer ctx.Delete("handled")
		next.ServeHTTP(flw, req)
	})
}