http-enc-res-hdr.lua 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. -- 功能:编码 HTTP 返回头
  2. -- 阶段:header_filter_by_lua
  3. -- 备注:
  4. -- aceh = HTTP 返回头的 access-control-expose-headers 字段
  5. --
  6. if
  7. ngx.req.get_method() == 'GET' and
  8. not ngx.ctx._hasCookie
  9. then
  10. end
  11. -- 无论浏览器是否支持,aceh 始终包含 *
  12. local expose = '*'
  13. -- 该值为 true 表示浏览器不支持 aceh: *,需返回详细的头部列表
  14. local detail = ngx.ctx._acehOld
  15. -- 由于接口路径固定,为避免被缓存,以请求头的 --url 值区分缓存
  16. local vary = '--url'
  17. local h, err = ngx.resp.get_headers()
  18. for k, v in pairs(h) do
  19. if
  20. -- 这些头有特殊意义,需要转义 --
  21. k == 'access-control-allow-origin' or
  22. k == 'access-control-expose-headers' or
  23. k == 'location' or
  24. k == 'set-cookie'
  25. then
  26. if type(v) == 'table' then
  27. for i = 1, #v do
  28. local x = i .. '-' .. k
  29. ngx.header[x] = v[i]
  30. if detail then
  31. expose = expose .. ',' .. x
  32. end
  33. end
  34. else
  35. local x = '--' .. k
  36. ngx.header[x] = v
  37. if detail then
  38. expose = expose .. ',' .. x
  39. end
  40. end
  41. ngx.header[k] = nil
  42. elseif k == 'vary' then
  43. if type(v) == 'table' then
  44. vary = vary .. ',' .. table.concat(v, ',')
  45. else
  46. vary = vary .. ',' .. v
  47. end
  48. elseif detail and
  49. -- 非简单头无法被 fetch 读取,需添加到 aceh 列表 --
  50. -- https://developer.mozilla.org/en-US/docs/Glossary/Simple_response_header
  51. k ~= 'cache-control' and
  52. k ~= 'content-language' and
  53. k ~= 'content-type' and
  54. k ~= 'expires' and
  55. k ~= 'last-modified' and
  56. k ~= 'pragma'
  57. then
  58. expose = expose .. ',' .. k
  59. end
  60. end
  61. if detail then
  62. expose = expose .. ',--s'
  63. ngx.header['--t'] = '1'
  64. end
  65. ngx.header['access-control-expose-headers'] = expose
  66. ngx.header['access-control-allow-origin'] = '*'
  67. ngx.header['vary'] = vary
  68. ngx.header['--s'] = ngx.status
  69. ngx.status = 200