Kong提供了一个自定义错误界面,该界面可以在Kong配置文件中配置,用于显示自定义API错误消息。下面是一个简单的示例:
在Kong配置文件中添加以下内容:
custom_plugins = myplugin
然后,在myplugin插件中添加以下代码:
local _M = {}
function _M.execute(conf)
return function (ctx)
if (ngx.status == 403) then
ngx.header.content_type = "application/json"
ngx.say('{"message": "您没有访问此API的权限"}')
ngx.exit(ngx.HTTP_FORBIDDEN)
end
end
end
return _M
在上面的插件代码中,我们检查HTTP响应代码(nginx.status),然后将自定义JSON消息写入ngx.say并将HTTP响应代码设置为ngx.exit。
在这个例子中,我们创建了一个403 HTTP响应并返回{"message": "您没有访问此API的权限"}。
要在Kong中使用此插件,需要在API上添加myplugin插件。
$ curl -i -X POST http://kong:8001/apis/{api}/plugins \
--data name=myplugin \
--data config.some_param=foo
最后,重新加载Kong的配置使自定义错误消息生效。
$ kong reload