feature: 新增 `response` 拦截器,目前暂时只支持替换响应头 (#295)

pull/297/head
王良 2024-04-14 03:47:53 +08:00 committed by GitHub
parent 5d61e4dfe1
commit 97de211cfb
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 71 additions and 1 deletions

View File

@ -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
}
}

View File

@ -13,6 +13,7 @@ const sni = require('./impl/req/sni')
// response interceptor impls
const cacheRes = require('./impl/res/cacheRes')
const script = require('./impl/res/script')
const response = require('./impl/res/response')
module.exports = [
// request interceptor impls
@ -22,5 +23,5 @@ module.exports = [
proxy, sni,
// response interceptor impls
cacheRes, script
cacheRes, script, response
]