Apisix通过内置基本插件直接返回静态内容的两种方式(echo或serverless插件)

apisix返回静态内容, 不需要额外的nginx进程/容器, 通过apisix内置插件实现

2024-06-23

背景

在nginx中, 如果想要配置一个接口返回静态内容(文本/json), 非常简单. 但是在apisix中, 会发现它没有这样的静态路由配置,

这时候对于从startup教程走过来的用户, 常规的想法是启动一个nginx容器返回静态内容, 然后在apisix中配置路由的upstream到nginx入口

但是其实并不需要启动一个nginx, 使用apisix的echo插件或serverless插件都可以实现返回静态内容

方法

注意的事项: 创建路由时不配置upstream部分

  1. 如果在dashboard中创建路由, 需要手动删除默认的upstream
  2. api创建时, 不指定upstream部分

echo, 返回静态内容

"echo": {  
    "body": "any static content"  
}

serverless 返回动态的content

代码是用 Lua 编写的,通常用于 OpenResty 或 NGINX with Lua 模块环境中

示例: 返回json, 包含一个固定msg和一个源ip(如果有cdn,从cf-connecting-ip头中获取)

代码内容:

snippet
return function(conf, ctx)
    local cjson = require "cjson"
    local client_ip = ngx.var.remote_addr
    local real_ip = ngx.var.http_cf_connecting_ip
    if real_ip then
        client_ip = real_ip
    end
    local response = { ip = client_ip, msg = "docker service only" }
    ngx.header.content_type = "application/json"
    ngx.say(cjson.encode(response))
    ngx.exit(ngx.HTTP_OK)
end

逐行解释如下:

  1. return function(conf, ctx):定义并返回一个匿名函数,接受两个参数 confctx
  2. local cjson = require "cjson":引入 Lua 的 JSON 库 cjson
  3. local client_ip = ngx.var.remote_addr:获取客户端的 IP 地址。
  4. local real_ip = ngx.var.http_x_real_ip:从 HTTP 头中获取 "X-Real-IP"。
  5. if real_ip then client_ip = real_ip end:如果存在 "X-Real-IP",则用其替换客户端 IP 地址。
  6. local response = { ip = client_ip, msg = "docker service only" }:创建一个 Lua 表,包含客户端 IP 地址和消息 "docker service only"。
  7. ngx.header.content_type = "application/json":设置响应的内容类型为 application/json
  8. ngx.say(cjson.encode(response)):将 Lua 表编码为 JSON 格式并输出。
  9. ngx.exit(ngx.HTTP_OK):以 HTTP 200 OK 状态码结束请求。

单行格式带转义符

return function(conf, ctx) local cjson = require \"cjson\"; local client_ip = ngx.var.remote_addr; local real_ip = ngx.var.http_cf_connecting_ip; if real_ip then client_ip = real_ip end; local response = { ip = client_ip, msg = \"docker service only\" }; ngx.header.content_type = \"application/json\"; ngx.say(cjson.encode(response)); ngx.exit(ngx.HTTP_OK); end

© api2o.com:: a website of blog, tools, APIs. 一个包含: 博客、在线工具、API 的网站. All rights reserved.