# HG changeset patch # User Kim Alvefur # Date 1614706693 -3600 # Node ID eea62d30ae084938e88a2d02d0362ece66ee3cfe # Parent f877a4d3770b384b2a6f0750ca224eac122683d8 mod_rest: Add option for serving interactive openapi documentation Swagger not included. diff -r f877a4d3770b -r eea62d30ae08 mod_rest/apidemo.lib.lua --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mod_rest/apidemo.lib.lua Tue Mar 02 18:38:13 2021 +0100 @@ -0,0 +1,44 @@ + +local _M = {}; + +local api_demo = module:get_option_path("rest_demo_resources", nil); +local http_files = require "net.http.files"; + +local mime_map = module:shared("/*/http_files/mime").types or {css = "text/css"; js = "application/javascript"}; +_M.resources = http_files.serve({ + path = api_demo; + mime_map = mime_map; + }); + +local index do + local f = assert(io.open(api_demo.."/index.html"), "'api_demo_resources' should point to the 'dist' directory"); + index = f:read("*a"); + f:close(); + + -- SUCH HACK, VERY GSUB, WOW! + index = index:gsub("(%s?url%s*:%s*)%b\"\"", string.format("%%1%q", module:http_url().."/demo/openapi.yaml"), 1); +end + +do + local f = module:load_resource("openapi.yaml"); + _M.schema = { + body = f:read("*a"); + } + f:close(); +end + +_M.redirect = { + status_code = 303; + headers = { + location = module:http_url().."/demo/"; + }; +}; + +_M.main_page = { + headers = { + content_type = "text/html"; + }; + body = index; +} + +return _M diff -r f877a4d3770b -r eea62d30ae08 mod_rest/mod_rest.lua --- a/mod_rest/mod_rest.lua Tue Mar 02 18:35:54 2021 +0100 +++ b/mod_rest/mod_rest.lua Tue Mar 02 18:38:13 2021 +0100 @@ -309,6 +309,11 @@ end end +local demo_handlers = {}; +if module:get_option_path("rest_demo_resources", nil) then + demo_handlers = module:require"apidemo"; +end + -- Handle stanzas submitted via HTTP module:depends("http"); module:provides("http", { @@ -316,6 +321,12 @@ POST = handle_request; ["POST /*"] = handle_request; ["GET /*"] = handle_request; + + -- Only if api_demo_resources are set + ["GET /"] = demo_handlers.redirect; + ["GET /demo/"] = demo_handlers.main_page; + ["GET /demo/openapi.yaml"] = demo_handlers.schema; + ["GET /demo/*"] = demo_handlers.resources; }; });