Pular para o conteúdo

Endpoints HTTP

Endpoints (http.endpoint) definem handlers de rota HTTP que executam funções Lua.

- name: get_user
kind: http.endpoint
meta:
router: app:api_router
method: GET
path: /users/{id}
func: app.users:get_user
CampoTipoObrigatórioDescrição
meta.routerregistry.IDNãoRoteador pai (padrão: o único roteador se exatamente um estiver registrado)
methodstringSimMétodo HTTP
pathstringSimPadrão de caminho URL
funcregistry.IDSimFunção a executar

Métodos suportados:

MétodoCaso de Uso
GETRecuperar recursos
POSTCriar recursos
PUTSubstituir recursos
PATCHAtualização parcial
DELETERemover recursos
HEADApenas headers
OPTIONSPreflight CORS (tratado automaticamente)
TRACELoopback de diagnóstico

Use sintaxe {param} para parâmetros de URL:

- name: get_user
kind: http.endpoint
method: GET
path: /users/{id}
func: get_user
- name: get_user_post
kind: http.endpoint
method: GET
path: /users/{user_id}/posts/{post_id}
func: get_user_post

Acesso no handler:

local http = require("http")
local function handler()
local req = http.request()
local user_id = req:param("id")
local post_id = req:param("post_id")
end

Capture caminho restante com {path...}:

- name: file_handler
kind: http.endpoint
method: GET
path: /files/{path...}
func: serve_file
local function handler()
local req = http.request()
local file_path = req:param("path")
-- /files/docs/readme.md -> path = "docs/readme.md"
end

Funções de endpoint obtêm objetos de requisição e resposta do módulo http:

local http = require("http")
local json = require("json")
local function handler()
local req = http.request()
local res = http.response()
-- Lê requisição
local body = req:body()
local user_id = req:param("id")
local page = req:query("page")
local auth = req:header("Authorization")
-- Processa
local user = get_user(user_id)
-- Escreve resposta
res:set_content_type(http.CONTENT.JSON)
res:set_status(http.STATUS.OK)
res:write_json(user)
end
return { handler = handler }
MétodoRetornaDescrição
req:method()stringMétodo HTTP
req:path()stringCaminho da requisição
req:param(name)stringParâmetro de URL
req:params()tableTodos os parâmetros de caminho
req:query(name)stringParâmetro de query
req:query_params()tableTodos os parâmetros de query
req:header(name)stringHeader da requisição
req:body()stringCorpo da requisição
req:body_json()table, errorAnalisa corpo JSON
req:has_body()booleanVerifica se existe corpo
req:content_type()stringTipo de conteúdo
req:content_length()numberTamanho do corpo em bytes
req:host()stringNome do host
req:remote_addr()stringEndereço IP do cliente
req:accepts(type)booleanNegociação de conteúdo
req:is_content_type(type)booleanVerifica tipo de conteúdo
req:stream()StreamCorpo como stream para arquivos grandes
req:parse_multipart(max?)table, errorAnalisa formulário multipart
MétodoDescrição
res:set_status(code)Define código de status HTTP
res:set_header(name, value)Define header de resposta
res:set_content_type(type)Define tipo de conteúdo
res:write(data)Escreve corpo bruto
res:write_json(data)Escreve resposta JSON
res:write_event(data)Envia evento SSE
res:set_transfer(encoding)Define modo de transferência (SSE, chunked)
res:flush()Descarrega resposta para o cliente

Padrão comum para APIs JSON:

local http = require("http")
local function handler()
local req = http.request()
local res = http.response()
local data, err = req:body_json()
if err then
res:set_status(http.STATUS.BAD_REQUEST)
res:write_json({error = "Invalid JSON"})
return
end
local result = process(data)
res:set_status(http.STATUS.OK)
res:write_json(result)
end
return { handler = handler }
local http = require("http")
local function api_error(res, status, code, message)
res:set_status(status)
res:write_json({
error = {
code = code,
message = message
}
})
end
local function handler()
local req = http.request()
local res = http.response()
local user_id = req:param("id")
local user, err = db.get_user(user_id)
if err then
if errors.is(err, errors.NOT_FOUND) then
return api_error(res, http.STATUS.NOT_FOUND, "USER_NOT_FOUND", "User not found")
end
return api_error(res, http.STATUS.INTERNAL_ERROR, "INTERNAL_ERROR", "Server error")
end
res:set_status(http.STATUS.OK)
res:write_json(user)
end
return { handler = handler }
entries:
- name: users_router
kind: http.router
prefix: /api/users
middleware:
- cors
- compress
- name: list_users
kind: http.endpoint
meta:
router: users_router
method: GET
path: /
func: app.users:list
- name: get_user
kind: http.endpoint
meta:
router: users_router
method: GET
path: /{id}
func: app.users:get
- name: create_user
kind: http.endpoint
meta:
router: users_router
method: POST
path: /
func: app.users:create
- name: update_user
kind: http.endpoint
meta:
router: users_router
method: PUT
path: /{id}
func: app.users:update
- name: delete_user
kind: http.endpoint
meta:
router: users_router
method: DELETE
path: /{id}
func: app.users:delete
- name: admin_endpoint
kind: http.endpoint
meta:
router: admin_router
method: POST
path: /settings
func: app.admin:update_settings
post_middleware:
- endpoint_firewall
post_options:
endpoint_firewall.action: "admin"