Skip to content

Commit

Permalink
Handle compressed response in openvsx proxy
Browse files Browse the repository at this point in the history
  • Loading branch information
jeanp413 committed Apr 4, 2022
1 parent 8ad398e commit d979e61
Showing 1 changed file with 23 additions and 5 deletions.
28 changes: 23 additions & 5 deletions components/openvsx-proxy/pkg/modifyresponse.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package pkg

import (
"bytes"
"compress/gzip"
"fmt"
"io/ioutil"
"net/http"
Expand Down Expand Up @@ -48,19 +49,19 @@ func (o *OpenVSXProxy) ModifyResponse(r *http.Response) error {
return nil
}

body, err := ioutil.ReadAll(r.Body)
rawBody, err := ioutil.ReadAll(r.Body)
if err != nil {
log.WithFields(logFields).WithError(err).Error("error reading response body")
log.WithFields(logFields).WithError(err).Error("error reading response raw body")
return err
}
r.Body.Close()
r.Body = ioutil.NopCloser(bytes.NewBuffer(body))
r.Body = ioutil.NopCloser(bytes.NewBuffer(rawBody))

if r.StatusCode >= 500 || r.StatusCode == http.StatusTooManyRequests || r.StatusCode == http.StatusRequestTimeout {
// use cache if exists
bodyLogField := "(binary)"
if utf8.Valid(body) {
bodyStr := string(body)
if utf8.Valid(rawBody) {
bodyStr := string(rawBody)
truncatedSuffix := ""
if len(bodyStr) > 500 {
truncatedSuffix = "... [truncated]"
Expand Down Expand Up @@ -93,8 +94,25 @@ func (o *OpenVSXProxy) ModifyResponse(r *http.Response) error {
}

// no error (status code < 500)
body := rawBody
contentType := r.Header.Get("Content-Type")
if strings.HasPrefix(contentType, "application/json") {
if strings.EqualFold(r.Header.Get("Content-Encoding"), "gzip") {
gzipReader, err := gzip.NewReader(ioutil.NopCloser(bytes.NewBuffer(rawBody)))
if err != nil {
log.WithFields(logFields).WithError(err)
}

body, err = ioutil.ReadAll(gzipReader)
if err != nil {
log.WithFields(logFields).WithError(err).Error("error reading response body")
return err
}
gzipReader.Close()

r.Header.Del("Content-Encoding")
}

if log.Log.Level >= logrus.DebugLevel {
log.WithFields(logFields).Debugf("replacing %d occurence(s) of '%s' in response body ...", strings.Count(string(body), o.Config.URLUpstream), o.Config.URLUpstream)
}
Expand Down

0 comments on commit d979e61

Please sign in to comment.