@@ -103,20 +103,40 @@ const handler = (route, proxy, proxyHandler) => async (req, res, next) => {
103
103
104
104
const onRequestNoOp = ( req , res ) => { }
105
105
const onResponse = async ( req , res , stream ) => {
106
- if ( ! res . hasHeader ( 'content-length' ) ) {
106
+ const TRANSFER_ENCODING_HEADER_NAME = 'transfer-encoding'
107
+ const chunked = stream . headers [ TRANSFER_ENCODING_HEADER_NAME ]
108
+ ? stream . headers [ TRANSFER_ENCODING_HEADER_NAME ] . endsWith ( 'chunked' )
109
+ : false
110
+
111
+ if ( req . headers . connection === 'close' && chunked ) {
107
112
try {
108
- const resBuffer = Buffer . concat ( await toArray ( stream ) )
109
- res . setHeader ( 'content-length' , '' + Buffer . byteLength ( resBuffer ) )
110
- res . statusCode = stream . statusCode
111
- res . end ( resBuffer )
113
+ // remove transfer-encoding header
114
+ const transferEncoding = stream . headers [ TRANSFER_ENCODING_HEADER_NAME ] . replace ( / ( , ( ) ? ) ? c h u n k e d / , '' )
115
+ if ( transferEncoding ) {
116
+ res . setHeader ( TRANSFER_ENCODING_HEADER_NAME , transferEncoding )
117
+ } else {
118
+ res . removeHeader ( TRANSFER_ENCODING_HEADER_NAME )
119
+ }
120
+
121
+ if ( ! stream . headers [ 'content-length' ] ) {
122
+ // pack all pieces into 1 buffer to calculate content length
123
+ const resBuffer = Buffer . concat ( await toArray ( stream ) )
124
+
125
+ // add content-length header and send the merged response buffer
126
+ res . setHeader ( 'content-length' , '' + Buffer . byteLength ( resBuffer ) )
127
+ res . statusCode = stream . statusCode
128
+ res . end ( resBuffer )
129
+
130
+ return
131
+ }
112
132
} catch ( err ) {
113
133
res . statusCode = 500
114
134
res . end ( err . message )
115
135
}
116
- } else {
117
- res . statusCode = stream . statusCode
118
- pump ( stream , res )
119
136
}
137
+
138
+ res . statusCode = stream . statusCode
139
+ pump ( stream , res )
120
140
}
121
141
122
142
module . exports = gateway
0 commit comments