Add gzip compression

This commit is contained in:
video-prize-ranch 2024-03-27 17:01:45 -04:00
parent dd6d8bd60f
commit 6f7e694fd4
No known key found for this signature in database
2 changed files with 41 additions and 28 deletions

View file

@ -1,6 +1,7 @@
package upstream
import (
"compress/gzip"
"errors"
"fmt"
"io"
@ -97,7 +98,10 @@ func (o *Options) Upstream(ctx *context.Context, giteaClient *gitea.Client, redi
log.Debug().Msg("Preparing")
reader, header, statusCode, err := giteaClient.ServeRawContent(o.TargetOwner, o.TargetRepo, o.TargetBranch, o.TargetPath)
// Check if gzip is supported
acceptsGzip := strings.Contains(ctx.Req.Header.Get("Accept-Encoding"), "gzip")
reader, header, statusCode, err := giteaClient.ServeRawContent(o.TargetOwner, o.TargetRepo, o.TargetBranch, o.TargetPath, acceptsGzip)
if reader != nil {
defer reader.Close()
}
@ -197,6 +201,19 @@ func (o *Options) Upstream(ctx *context.Context, giteaClient *gitea.Client, redi
return true
}
// Decompress response if gzip is not supported
r := reader
if !acceptsGzip {
r, err = gzip.NewReader(reader)
if err != nil {
log.Error().Err(err).Msgf("Couldn't decompress for %q", o.TargetPath)
html.ReturnErrorPage(ctx, "", http.StatusInternalServerError)
return true
}
} else {
ctx.RespWriter.Header().Set("Content-Encoding", "gzip")
}
// Set ETag & MIME
o.setHeader(ctx, header)
@ -206,7 +223,7 @@ func (o *Options) Upstream(ctx *context.Context, giteaClient *gitea.Client, redi
// Write the response body to the original request
if reader != nil {
_, err := io.Copy(ctx.RespWriter, reader)
_, err := io.Copy(ctx.RespWriter, r)
if err != nil {
log.Error().Err(err).Msgf("Couldn't write body for %q", o.TargetPath)
html.ReturnErrorPage(ctx, "", http.StatusInternalServerError)