Skip to content

Commit

Permalink
Merge pull request #16 from tocktix/handle-gzip-encoding-better
Browse files Browse the repository at this point in the history
Alter if `gzip` compression is used based on client's `Accept-Encoding` contents.
  • Loading branch information
daichirata authored Sep 9, 2022
2 parents ac5d8c6 + f279972 commit 4ca68f7
Showing 1 changed file with 10 additions and 4 deletions.
14 changes: 10 additions & 4 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"log"
"net/http"
"strconv"
"strings"
"time"

"cloud.google.com/go/storage"
Expand Down Expand Up @@ -100,7 +101,8 @@ func wrapper(fn func(w http.ResponseWriter, r *http.Request)) http.HandlerFunc {

func proxy(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
obj := client.Bucket(params["bucket"]).Object(params["object"]).ReadCompressed(false)
gzipAcceptable := clientAcceptsGzip(r)
obj := client.Bucket(params["bucket"]).Object(params["object"]).ReadCompressed(gzipAcceptable)
attr, err := obj.Attrs(ctx)
if err != nil {
handleError(w, err)
Expand All @@ -121,17 +123,21 @@ func proxy(w http.ResponseWriter, r *http.Request) {
handleError(w, err)
return
}
attrC := objr.Attrs.ContentEncoding
setTimeHeader(w, "Last-Modified", attr.Updated)
setStrHeader(w, "Content-Type", attr.ContentType)
setStrHeader(w, "Content-Language", attr.ContentLanguage)
setStrHeader(w, "Cache-Control", attr.CacheControl)
setStrHeader(w, "Content-Encoding", attrC)
setStrHeader(w, "Content-Encoding", objr.Attrs.ContentEncoding)
setStrHeader(w, "Content-Disposition", attr.ContentDisposition)
setIntHeader(w, "Content-Length", attr.Size)
setIntHeader(w, "Content-Length", objr.Attrs.Size)
io.Copy(w, objr)
}

func clientAcceptsGzip(r *http.Request) bool {
acceptHeader := r.Header.Get("Accept-Encoding")
return strings.Contains(acceptHeader, "gzip")
}

func main() {
flag.Parse()

Expand Down

0 comments on commit 4ca68f7

Please sign in to comment.