diff options
author | Gabriel A. Giovanini <mail@gabrielgio.me> | 2025-06-04 12:51:47 +0200 |
---|---|---|
committer | Gabriel A. Giovanini <mail@gabrielgio.me> | 2025-06-04 12:51:47 +0200 |
commit | 3739c9e14b0c65a59a520dbfefa459e43af3bf20 (patch) | |
tree | 3731016eb12180f12817ed1094eee8cb0f67b49b /pkg/ext/compression.go | |
parent | 90b2a890096ee9ab3ff84c57542b5220aa9ebe4c (diff) | |
download | cerrado-3739c9e14b0c65a59a520dbfefa459e43af3bf20.tar.gz cerrado-3739c9e14b0c65a59a520dbfefa459e43af3bf20.tar.bz2 cerrado-3739c9e14b0c65a59a520dbfefa459e43af3bf20.zip |
feat: Wrap request
Since request is not a interface I need to create a wraper for it so I
can extend it later.
Diffstat (limited to 'pkg/ext/compression.go')
-rw-r--r-- | pkg/ext/compression.go | 31 |
1 files changed, 25 insertions, 6 deletions
diff --git a/pkg/ext/compression.go b/pkg/ext/compression.go index 6c7a219..d3a3df1 100644 --- a/pkg/ext/compression.go +++ b/pkg/ext/compression.go @@ -15,18 +15,37 @@ import ( "github.com/klauspost/compress/zstd" ) -var ( - errInvalidParam = errors.New("Invalid weighted param") -) +var errInvalidParam = errors.New("Invalid weighted param") type CompressionResponseWriter struct { innerWriter http.ResponseWriter compressWriter io.Writer } -func Compress(next http.HandlerFunc) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { +func Compress(next HandlerFunc) HandlerFunc { + return func(w http.ResponseWriter, r *Request) { + // TODO: hand this better + if strings.HasSuffix(r.URL.Path, ".tar.gz") { + next(w, r) + return + } + + if accept, ok := r.Header["Accept-Encoding"]; ok { + if compress, algo := GetCompressionWriter(u.FirstOrZero(accept), w); algo != "" { + defer compress.Close() + w.Header().Add("Content-Encoding", algo) + w = &CompressionResponseWriter{ + innerWriter: w, + compressWriter: compress, + } + } + } + next(w, r) + } +} +func Decompress(next http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { // TODO: hand this better if strings.HasSuffix(r.URL.Path, ".tar.gz") { next(w, r) @@ -61,12 +80,12 @@ func GetCompressionWriter(header string, inner io.Writer) (io.WriteCloser, strin default: return nil, "" } - } func (c *CompressionResponseWriter) Header() http.Header { return c.innerWriter.Header() } + func (c *CompressionResponseWriter) Write(b []byte) (int, error) { return c.compressWriter.Write(b) } |