Two Ways for Apisix to Return Static Content Directly via Built-in Plugins (echo or serverless plugin)
Apisix returns static content without the need for an additional nginx process/container, achieved through Apisix built-in plugins.
Background
In nginx, it is very easy to configure an interface to return static content (text/json). However, in Apisix, you will find that there is no such static route configuration.
At this point, users who have followed the startup tutorial typically think of starting an nginx container to return static content, and then configuring the upstream in Apisix to route to the nginx entry.
However, it is actually not necessary to start an nginx. You can return static content using either Apisix's echo plugin or the serverless plugin.
Methods
Note: Do not configure the upstream section when creating the route.
- If you create a route in the dashboard, you need to manually delete the default upstream.
- When creating the API, do not specify the upstream section.
Echo: Return Static Content
"echo": {
"body": "any static content"
}
Serverless: Return Dynamic Content
The code is written in Lua, typically used in OpenResty or NGINX with Lua module environments.
Example: Return Json, Including a Fixed Msg and a Source IP (If there is a CDN, obtain it from the cf-connecting-ip header)
Code content:
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
Explanation line by line:
return function(conf, ctx): Defines and returns an anonymous function that accepts two parameters,confandctx.local cjson = require "cjson": Imports Lua's JSON librarycjson.local client_ip = ngx.var.remote_addr: Gets the client's IP address.local real_ip = ngx.var.http_x_real_ip: Retrieves "X-Real-IP" from the HTTP header.if real_ip then client_ip = real_ip end: If "X-Real-IP" exists, replace the client IP address with it.local response = { ip = client_ip, msg = "docker service only" }: Creates a Lua table containing the client IP address and the message "docker service only".ngx.header.content_type = "application/json": Sets the response content type toapplication/json.ngx.say(cjson.encode(response)): Encodes the Lua table to JSON format and outputs it.ngx.exit(ngx.HTTP_OK): Ends the request with an HTTP 200 OK status code.
Single Line Format with Escape Characters
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