GZip compression support

This commit is contained in:
DarthSim
2017-06-27 03:41:37 +03:00
parent 3fa721bee0
commit e04696b89b
3 changed files with 24 additions and 6 deletions

View File

@@ -14,6 +14,7 @@ Imgproxy is 12factor-ready and can be configured with env variables:
* IMGPROXY_MAX_SRC_DIMENSION - the maximum dimension of source image. Images with larger size will be rejected. Default: 4096;
* IMGPROXY_QUALITY - quality of a result image. Default: 80;
* IMGPROXY_COMPRESSION - compression of a result image. Default: 6;
* IMGPROXY_COMPRESSION - GZip compression level. Default: 5;
* IMGPROXY_KEY - hex-encoded key
* IMGPROXY_SALT - hex-encoded salt

View File

@@ -80,8 +80,9 @@ type config struct {
MaxSrcDimension int
Quality int
Compression int
Quality int
Compression int
GZipCompression int
Key []byte
Salt []byte
@@ -94,6 +95,7 @@ var conf = config{
MaxSrcDimension: 4096,
Quality: 80,
Compression: 6,
GZipCompression: 5,
}
func init() {
@@ -109,6 +111,7 @@ func init() {
intEnvConfig(&conf.Quality, "IMGPROXY_QUALITY")
intEnvConfig(&conf.Compression, "IMGPROXY_COMPRESSION")
intEnvConfig(&conf.GZipCompression, "IMGPROXY_GZIP_COMPRESSION")
hexEnvConfig(&conf.Key, "IMGPROXY_KEY")
hexEnvConfig(&conf.Salt, "IMGPROXY_SALT")

22
main.go
View File

@@ -2,6 +2,7 @@ package main
import (
"bytes"
"compress/gzip"
"encoding/base64"
"errors"
"fmt"
@@ -88,12 +89,25 @@ func logResponse(status int, msg string) {
log.Printf("|\033[7;%dm %d \033[0m| %s\n", color, status, msg)
}
func respondWithImage(rw http.ResponseWriter, data []byte, imgURL string, po processingOptions) {
func respondWithImage(r *http.Request, rw http.ResponseWriter, data []byte, imgURL string, po processingOptions) {
logResponse(200, fmt.Sprintf("Processed: %s; %+v", imgURL, po))
rw.WriteHeader(200)
gzipped := strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") && conf.GZipCompression > 0
rw.Header().Set("Content-Type", imageContentType(data))
rw.Write(data)
if gzipped {
rw.Header().Set("Content-Encoding", "gzip")
}
rw.WriteHeader(200)
if gzipped {
gz, _ := gzip.NewWriterLevel(rw, conf.GZipCompression)
gz.Write(data)
gz.Close()
} else {
rw.Write(data)
}
}
func respondWithError(rw http.ResponseWriter, status int, err error, msg string) {
@@ -129,7 +143,7 @@ func (h httpHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
return
}
respondWithImage(rw, b, imgURL, procOpt)
respondWithImage(r, rw, b, imgURL, procOpt)
}
func main() {