@@ -6,6 +6,7 @@ package pkg
6
6
7
7
import (
8
8
"bytes"
9
+ "compress/gzip"
9
10
"fmt"
10
11
"io/ioutil"
11
12
"net/http"
@@ -48,19 +49,19 @@ func (o *OpenVSXProxy) ModifyResponse(r *http.Response) error {
48
49
return nil
49
50
}
50
51
51
- body , err := ioutil .ReadAll (r .Body )
52
+ rawBody , err := ioutil .ReadAll (r .Body )
52
53
if err != nil {
53
- log .WithFields (logFields ).WithError (err ).Error ("error reading response body" )
54
+ log .WithFields (logFields ).WithError (err ).Error ("error reading response raw body" )
54
55
return err
55
56
}
56
57
r .Body .Close ()
57
- r .Body = ioutil .NopCloser (bytes .NewBuffer (body ))
58
+ r .Body = ioutil .NopCloser (bytes .NewBuffer (rawBody ))
58
59
59
60
if r .StatusCode >= 500 || r .StatusCode == http .StatusTooManyRequests || r .StatusCode == http .StatusRequestTimeout {
60
61
// use cache if exists
61
62
bodyLogField := "(binary)"
62
- if utf8 .Valid (body ) {
63
- bodyStr := string (body )
63
+ if utf8 .Valid (rawBody ) {
64
+ bodyStr := string (rawBody )
64
65
truncatedSuffix := ""
65
66
if len (bodyStr ) > 500 {
66
67
truncatedSuffix = "... [truncated]"
@@ -93,13 +94,42 @@ func (o *OpenVSXProxy) ModifyResponse(r *http.Response) error {
93
94
}
94
95
95
96
// no error (status code < 500)
97
+ body := rawBody
96
98
contentType := r .Header .Get ("Content-Type" )
97
99
if strings .HasPrefix (contentType , "application/json" ) {
100
+ compressedResponse := strings .EqualFold (r .Header .Get ("Content-Encoding" ), "gzip" )
101
+ if compressedResponse {
102
+ gzipReader , err := gzip .NewReader (ioutil .NopCloser (bytes .NewBuffer (rawBody )))
103
+ if err != nil {
104
+ log .WithFields (logFields ).WithError (err )
105
+ return nil
106
+ }
107
+
108
+ body , err = ioutil .ReadAll (gzipReader )
109
+ if err != nil {
110
+ log .WithFields (logFields ).WithError (err ).Error ("error reading compressed response body" )
111
+ return nil
112
+ }
113
+ gzipReader .Close ()
114
+ }
115
+
98
116
if log .Log .Level >= logrus .DebugLevel {
99
117
log .WithFields (logFields ).Debugf ("replacing %d occurence(s) of '%s' in response body ..." , strings .Count (string (body ), o .Config .URLUpstream ), o .Config .URLUpstream )
100
118
}
101
119
bodyStr := strings .ReplaceAll (string (body ), o .Config .URLUpstream , o .Config .URLLocal )
102
120
body = []byte (bodyStr )
121
+
122
+ if compressedResponse {
123
+ var b bytes.Buffer
124
+ gzipWriter := gzip .NewWriter (& b )
125
+ _ , err = gzipWriter .Write (body )
126
+ if err != nil {
127
+ log .WithFields (logFields ).WithError (err ).Error ("error writing compressed response body" )
128
+ return nil
129
+ }
130
+ gzipWriter .Close ()
131
+ body = b .Bytes ()
132
+ }
103
133
} else {
104
134
log .WithFields (logFields ).Debugf ("response is not JSON but '%s', skipping replacing '%s' in response body" , contentType , o .Config .URLUpstream )
105
135
}
0 commit comments