client/lua: handle the api server being offline

This commit is contained in:
Ben Klein 2021-07-10 15:25:09 -04:00
parent 38080611d5
commit 3ec013b210
2 changed files with 30 additions and 19 deletions

View file

@ -1,21 +1,35 @@
-- Set the response content type back to HTML
ngx.header.content_type = 'text/html';
ngx.req.read_body() ngx.req.read_body()
local page_html = ngx.location.capture("/index.htm") local page_html = ngx.location.capture("/index.htm").body
local before_content, placeholder, after_content
before_content, placeholder, after_content = page_html:match(
string.format("^(.*)(%s)(.*)$", html_head_tag_replacement_str)
)
-- check for placeholder to replace
if not placeholder then
ngx.log(ngx.STDERR, "WARNING: Meta tag placeholder was not found in page html.")
ngx.say(page_html)
return
else
-- start the response
ngx.print(before_content)
end
ngx.req.set_header("Accept", "application/json") ngx.req.set_header("Accept", "application/json")
local server_info = cjson.decode((ngx.location.capture("/_internal_api/info")).body) local server_info_resp = ngx.location.capture("/_internal_api/info")
if server_info_resp.status ~= 200 then
-- local document = gumbo.parse(page_html.body) ngx.log(ngx.STDERR, "Failed to acquire server info from szurubooru API, unable to generate meta tags: HTTP status "..server_info_resp.status)
-- ngx.print(after_content)
-- function add_meta_tag (property, content) return
-- local new_element = document:createElement("meta") end
-- document.head:appendChild(new_element) local server_info = cjson.decode(server_info_resp.body)
-- new_element:setAttribute("property", property)
-- new_element:setAttribute("content", content)
-- end
local additional_tags = "" local additional_tags = ""
local function add_meta_tag (property, content) local function add_meta_tag (property, content)
additional_tags = additional_tags .. "<meta property=\"" .. property .. "\" content=\"" .. content:gsub('"', '\\"') .. "\"/>" additional_tags = additional_tags .. "<meta property=\"" .. property .. "\" content=\"" .. content:gsub('"', '\\"') .. "\"/>"
end end
@ -35,10 +49,6 @@ if ngx.var.request_uri_path:match('^/post') then
end end
end end
local final_response = page_html.body:gsub("{{ generated_head_tags }}", additional_tags) -- Once tags have been generated, write them and then finish the response
ngx.print(additional_tags)
-- Set the content type back to HTML ngx.print(after_content)
ngx.header.content_type = 'text/html';
-- ngx.say(page_html.body)
ngx.say(final_response)

View file

@ -31,6 +31,7 @@ http {
init_by_lua_block { init_by_lua_block {
cjson = require("cjson") cjson = require("cjson")
html_head_tag_replacement_str = "{{ generated_head_tags }}"
} }
server { server {