HTTP
HTTPリクエストを処理しレスポンスを構築。リクエストデータ、ルートパラメータ、ヘッダー、ボディ内容にアクセス。ステータスコード、ヘッダー、ストリーミングサポート付きでレスポンスを構築。
サーバー設定についてはHTTPサーバーを参照。
local http = require("http")リクエストへのアクセス
Section titled “リクエストへのアクセス”現在のHTTPリクエストコンテキストを取得:
local req = http.request()
-- オプション付きlocal req = http.request({ timeout = 5000, -- 5秒のボディ読み取りタイムアウト max_body = 10485760 -- 10MB最大ボディ})| パラメータ | 型 | 説明 |
|---|---|---|
options.timeout | integer | ボディ読み取りタイムアウト(ms)(デフォルト: 300000 / 5分) |
options.max_body | integer | 最大ボディサイズ(バイト単位)(デフォルト: 120MB) |
戻り値: Request, error
レスポンスへのアクセス
Section titled “レスポンスへのアクセス”現在のHTTPレスポンスコンテキストを取得:
local res = http.response()戻り値: Response, error
リクエストメソッド
Section titled “リクエストメソッド”method
Section titled “method”local method = req:method()
if method == http.METHOD.GET then return get_resource(id)elseif method == http.METHOD.POST then return create_resource(req:body_json())elseif method == http.METHOD.PUT then return update_resource(id, req:body_json())elseif method == http.METHOD.DELETE then return delete_resource(id)endlocal path = req:path()print(path) -- "/api/users/123"
-- パスに基づいてルーティングif path:match("^/api/") then return handle_api(req)end単一のクエリパラメータを取得。
-- GET /search?q=hello&page=2&limit=10local query = req:query("q") -- "hello"local page = req:query("page") -- "2"local missing = req:query("foo") -- nil
-- デフォルト値付きlocal page = tonumber(req:query("page")) or 1local limit = tonumber(req:query("limit")) or 20local sort = req:query("sort") or "created_at"query_params
Section titled “query_params”すべてのクエリパラメータを取得。同じキーに対する複数の値はカンマで結合。
-- GET /search?tags=lua&tags=go&active=truelocal params = req:query_params()-- {tags = "lua,go", active = "true"}
for key, value in pairs(params) do print(key .. ": " .. value)endheader
Section titled “header”local auth = req:header("Authorization")if not auth then res:set_status(401) return res:write_json({error = "Missing authorization"})end
local user_agent = req:header("User-Agent")local correlation_id = req:header("X-Correlation-ID") or uuid.v4()content_type
Section titled “content_type”Content-Typeヘッダーを取得。
local ct = req:content_type() -- "application/json; charset=utf-8"またはnilcontent_length
Section titled “content_length”Content-Lengthヘッダー値を取得。
local length = req:content_length() -- バイト数Hostヘッダーを取得。
local host = req:host() -- "example.com:8080"URLルートパラメータを取得(/users/:idのようなパスパターンから)。
-- ルート: /users/:id/posts/:post_idlocal user_id = req:param("id")local post_id = req:param("post_id")
-- パラメータの検証local id = req:param("id")if not id or not uuid.validate(id) then res:set_status(400) return res:write_json({error = "Invalid ID format"})endparams
Section titled “params”すべてのルートパラメータを取得。
-- ルート: /orgs/:org/repos/:repo/issues/:issuelocal p = req:params()-- {org = "acme", repo = "widget", issue = "123"}
local issue = get_issue(p.org, p.repo, p.issue)リクエストボディ全体を文字列として読み取り。
local body = req:body()
-- XMLを手動でパースif req:is_content_type("application/xml") then local data = parse_xml(body)end
-- デバッグ用に生のボディをログlogger.debug("Request body", {body = body, length = #body})body_json
Section titled “body_json”ボディをJSONとして読み取りパース。
local data, err = req:body_json()if err then res:set_status(400) return res:write_json({error = "Invalid JSON: " .. err:message()})end
-- 必須フィールドの検証if not data.name or not data.email then res:set_status(400) return res:write_json({error = "Missing required fields"})end
local user = create_user(data)has_body
Section titled “has_body”if req:has_body() then local data = req:body_json() process(data)else res:set_status(400) return res:write_json({error = "Request body required"})endis_content_type
Section titled “is_content_type”if not req:is_content_type("application/json") then res:set_status(415) return res:write_json({error = "Content-Type must be application/json"})endaccepts
Section titled “accepts”if req:accepts("application/json") then res:write_json(data)elseif req:accepts("text/html") then res:set_content_type("text/html") res:write(render_html(data))else res:set_status(406) res:write_json({error = "Cannot produce acceptable response"})endremote_addr
Section titled “remote_addr”local addr = req:remote_addr() -- "192.168.1.100:54321"
-- IPのみを抽出local ip = addr:match("^([^:]+)")
-- IPによるレート制限if rate_limiter:is_limited(ip) then res:set_status(429) return res:write_json({error = "Too many requests"})endparse_multipart
Section titled “parse_multipart”マルチパートフォームデータ(ファイルアップロード)をパース。オプションで max_memory integer を取ります(一時ファイルへ退避する前にメモリ上に保持するバイト数。デフォルト 32MB)。
local form, err = req:parse_multipart() -- または req:parse_multipart(8 * 1024 * 1024)if err then res:set_status(400) return res:write_json({error = "Invalid form data"})end
-- フォーム値にアクセスlocal title = form.values.titlelocal description = form.values.description
-- アップロードされたファイルにアクセスif form.files.avatar then local file = form.files.avatar[1] local filename = file:name() -- "photo.jpg" local size = file:size() -- 102400 local content_type = file:header("Content-Type") -- "image/jpeg"
-- ファイル内容を読み取り local stream = file:stream() local content = stream:read(0) stream:close()
-- ストレージに保存 storage.write("avatars/" .. filename, content)end
-- 複数ファイルの処理if form.files.documents then for _, file in ipairs(form.files.documents) do process_document(file) endendstream
Section titled “stream”大きなファイル用にリクエストボディをストリームとして取得。
local stream = req:stream()
-- チャンクで処理while true do local chunk, err = stream:read(65536) -- 64KBチャンク if err or not chunk then break end process_chunk(chunk)endstream:close()レスポンスメソッド
Section titled “レスポンスメソッド”set_status
Section titled “set_status”res:set_status(200)res:set_status(http.STATUS.CREATED)
-- 一般的なパターンres:set_status(201) -- Createdres:set_status(204) -- No Content(DELETE用)res:set_status(400) -- Bad Requestres:set_status(401) -- Unauthorizedres:set_status(403) -- Forbiddenres:set_status(404) -- Not Foundres:set_status(500) -- Internal Server Errorset_header
Section titled “set_header”res:set_header("X-Request-ID", correlation_id)res:set_header("Cache-Control", "max-age=3600")res:set_header("X-RateLimit-Remaining", tostring(remaining))
-- CORSヘッダーres:set_header("Access-Control-Allow-Origin", "*")res:set_header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE")res:set_header("Access-Control-Allow-Headers", "Content-Type, Authorization")set_content_type
Section titled “set_content_type”res:set_content_type("application/json")res:set_content_type(http.CONTENT.JSON)res:set_content_type("text/html; charset=utf-8")res:set_content_type("application/pdf")レスポンスボディに書き込み。
res:write("Hello, World!")
-- レスポンスを段階的に構築res:write("<html><body>")res:write("<h1>Title</h1>")res:write("<p>Content</p>")res:write("</body></html>")write_json
Section titled “write_json”値をJSONにエンコードして書き込み。
-- 成功レスポンスres:set_status(200)res:write_json({ data = users, total = count, page = page})
-- エラーレスポンスres:set_status(400)res:write_json({ error = "Validation failed", details = { {field = "email", message = "Invalid format"}, {field = "age", message = "Must be positive"} }})バッファリングされたデータをクライアントにフラッシュ。
set_transfer
Section titled “set_transfer”ストリーミング用の転送エンコーディングを設定。
-- チャンク転送res:set_transfer(http.TRANSFER.CHUNKED)for chunk in get_chunks() do res:write(chunk) res:flush()end
-- Server-Sent Eventsres:set_transfer(http.TRANSFER.SSE)write_event
Section titled “write_event”Server-Sent Eventを書き込み。
-- リアルタイム更新res:set_transfer(http.TRANSFER.SSE)
res:write_event({name = "connected", data = {client_id = client_id}})
for progress in task:progress() do res:write_event({name = "progress", data = {percent = progress}})end
res:write_event({name = "complete", data = {result = result}})
-- チャットメッセージres:write_event({name = "message", data = { from = "alice", text = "Hello!", timestamp = time.now():unix()}})HTTPメソッド
Section titled “HTTPメソッド”http.METHOD.GEThttp.METHOD.POSThttp.METHOD.PUThttp.METHOD.DELETEhttp.METHOD.PATCHhttp.METHOD.HEADhttp.METHOD.OPTIONSステータスコード
Section titled “ステータスコード”-- 成功 (2xx)http.STATUS.OK -- 200http.STATUS.CREATED -- 201http.STATUS.ACCEPTED -- 202http.STATUS.NO_CONTENT -- 204http.STATUS.PARTIAL_CONTENT -- 206
-- リダイレクト (3xx)http.STATUS.MOVED_PERMANENTLY -- 301http.STATUS.FOUND -- 302http.STATUS.SEE_OTHER -- 303http.STATUS.NOT_MODIFIED -- 304http.STATUS.TEMPORARY_REDIRECT -- 307http.STATUS.PERMANENT_REDIRECT -- 308
-- クライアントエラー (4xx)http.STATUS.BAD_REQUEST -- 400http.STATUS.UNAUTHORIZED -- 401http.STATUS.PAYMENT_REQUIRED -- 402http.STATUS.FORBIDDEN -- 403http.STATUS.NOT_FOUND -- 404http.STATUS.METHOD_NOT_ALLOWED -- 405http.STATUS.NOT_ACCEPTABLE -- 406http.STATUS.CONFLICT -- 409http.STATUS.GONE -- 410http.STATUS.UNPROCESSABLE -- 422http.STATUS.TOO_MANY_REQUESTS -- 429
-- サーバーエラー (5xx)http.STATUS.INTERNAL_ERROR -- 500 (alias: INTERNAL_SERVER_ERROR)http.STATUS.NOT_IMPLEMENTED -- 501http.STATUS.BAD_GATEWAY -- 502http.STATUS.SERVICE_UNAVAILABLE -- 503http.STATUS.GATEWAY_TIMEOUT -- 504http.STATUS.VERSION_NOT_SUPPORTED -- 505コンテンツタイプ
Section titled “コンテンツタイプ”http.CONTENT.JSON -- "application/json"http.CONTENT.FORM -- "application/x-www-form-urlencoded"http.CONTENT.MULTIPART -- "multipart/form-data"http.CONTENT.TEXT -- "text/plain"http.CONTENT.STREAM -- "application/octet-stream"http.TRANSFER.CHUNKED -- "chunked"http.TRANSFER.SSE -- "sse"エラータイプ
Section titled “エラータイプ”正確なエラー処理のためのモジュール固有のエラータイプ定数。
http.ERROR.PARSE_FAILED -- フォーム/マルチパートパースエラーhttp.ERROR.INVALID_STATE -- 無効なレスポンス状態http.ERROR.WRITE_FAILED -- レスポンス書き込みエラーhttp.ERROR.STREAM_ERROR -- ボディストリームエラー| 条件 | 種別 | 再試行可能 |
|---|---|---|
| HTTPコンテキストがない | errors.INTERNAL | no |
| ボディが大きすぎる | errors.INVALID | no |
| 読み取りタイムアウト | errors.INTERNAL | no |
| 無効なJSON | errors.INVALID | no |
| マルチパートではない | errors.INVALID | no |
| ヘッダーが既に送信済み | errors.INVALID | no |
| 書き込み失敗 | errors.INTERNAL | no |
エラーの処理についてはエラー処理を参照。