-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feature: 新增
response
拦截器,目前暂时只支持替换响应头 (#295)
- Loading branch information
1 parent
5d61e4d
commit 97de211
Showing
2 changed files
with
71 additions
and
1 deletion.
There are no files selected for viewing
69 changes: 69 additions & 0 deletions
69
packages/mitmproxy/src/lib/interceptor/impl/res/response.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
const lodash = require('lodash') | ||
|
||
function replaceHeaders (newHeaders, res, proxyRes) { | ||
if (newHeaders && !lodash.isEmpty(newHeaders)) { | ||
// 响应头Key统一转小写 | ||
for (const headerKey in newHeaders) { | ||
if (headerKey === headerKey.toLowerCase()) { | ||
continue | ||
} | ||
|
||
const value = newHeaders[headerKey] | ||
delete newHeaders[headerKey] | ||
newHeaders[headerKey.toLowerCase()] = value | ||
} | ||
|
||
// 原先响应头 | ||
const preHeaders = {} | ||
|
||
// 替换响应头 | ||
for (let i = 0; i < proxyRes.rawHeaders.length; i += 2) { | ||
const headerKey = proxyRes.rawHeaders[i] | ||
const headerKeyLower = headerKey.toLowerCase() | ||
|
||
const newHeaderValue = newHeaders[headerKeyLower] | ||
if (newHeaderValue) { | ||
preHeaders[headerKeyLower] = proxyRes.rawHeaders[i + 1] // 先保存原先响应头 | ||
|
||
proxyRes.rawHeaders[i + 1] = newHeaderValue | ||
delete newHeaders[headerKeyLower] | ||
} | ||
} | ||
// 新增响应头 | ||
for (const headerKey in newHeaders) { | ||
res.setHeader(headerKey, newHeaders[headerKey]) | ||
preHeaders[headerKey] = null // 标记原先响应头为null | ||
} | ||
|
||
// 返回原先响应头 | ||
return preHeaders | ||
} | ||
|
||
return null | ||
} | ||
|
||
module.exports = { | ||
name: 'response', | ||
priority: 203, | ||
replaceHeaders, | ||
responseIntercept (context, interceptOpt, req, res, proxyReq, proxyRes, ssl, next) { | ||
const { log } = context | ||
|
||
const responseConfig = interceptOpt.response | ||
|
||
let actions = '' | ||
|
||
// 替换响应头 | ||
if (replaceHeaders(responseConfig.headers, res, proxyRes)) { | ||
actions += 'headers' | ||
} | ||
|
||
if (actions) { | ||
res.setHeader('DS-Response-Interceptor', actions) | ||
log.info('response intercept: ' + actions) | ||
} | ||
}, | ||
is (interceptOpt) { | ||
return !!interceptOpt.response | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters