如何使用Lua代码在EnvoyFilter中重定向到登录页面?

我是Lua的新手,下面是我针对"EnvoyFilter"的内联代码。我搜索了一些文章和帖子,花了几个小时,但是没有找到合适的答案,因此发布这个问题。

场景是当我收到503错误代码时,我想重定向到登录页面。

             function envoy_on_response(response_handle)
                if response_handle:headers():get(":status") == "503" then
                  #TODO Redirect to http://login-page.com
                end
              end

任何帮助或建议都将是有用和受欢迎的。

[工作答案]

function envoy_on_response(response_handle)
  if response_handle:headers():get(":status") == "503" then
    response_handle:headers():replace("content-type", "text/html")
    response_handle:headers():replace(":status", "307")
    response_handle:headers():add("location", "https://login-page.com")
  end
end
点赞
用户10020419
用户10020419

你可以使用 302 Found 响应来指示用户的浏览器对登录页面进行新的请求。

可以像下面这样实现:

首先添加一些日志来验证正常工作。

然后替换头部中的 status 字段并将其设置为 302

最后,添加一个 location 字段到头部,其中包含您想要重定向到的 URL。

function envoy_on_response(response_handle)
    if response_handle:headers():get(":status") == "503" then
        response_handle:logInfo("Got status 503, redirect to login...")
        response_handle:headers():replace(":status", "302")
        response_handle:headers():add("location", "http://login-page.com")
    end
end

更多灵感请参见文档: https://www.envoyproxy.io/docs/envoy/latest/configuration/http/http_filters/lua_filter

说了这些,我想补充一点,这可能不是处理故障的好方法。用户不会被通知错误,而只会被重定向并落在登录页面,无法知道错误原因。

你想要解决什么问题?也许有更好的方法。

2020-11-05 13:03:31