-- 引入必要的库和模块 local cjson = require"cjson.safe" local http = require"resty.http" local uri = ngx.var.uri local args = ngx.req.get_uri_args() local method = ngx.req.get_method()
-- 根据 URI 匹配需要代理到哪个后端服务 local backend_url if uri == "/api/user"then backend_url = "http://user-service:8080" elseif uri == "/api/order"then backend_url = "http://order-service:8080" else ngx.exit(ngx.HTTP_NOT_FOUND) end
-- 创建一个 http 客户端 local httpc = http.new() httpc:set_timeout(5000)
-- 发起请求到后端服务 local res, err = httpc:request_uri(backend_url, { method = method, headers = ngx.req.get_headers(), query = args, body = ngx.req.read_body() and ngx.req.get_body_data(), })
-- 检查请求是否成功 ifnot res then ngx.log(ngx.ERR, "failed to request: ", err) ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR) end
-- 将后端服务返回的响应返回给客户端 ngx.status = res.status for k, v inpairs(res.headers) do ngx.header[k] = v end ngx.say(res.body)
以上示例代码是一个简单的网关实现,它会根据客户端请求的 URI 路径将请求转发到对应的后端服务,并将后端服务返回的响应返回给客户端。在实际使用中,还需要对请求进行安全性检查、负载均衡等处理,具体实现可以根据实际需求进行扩展。