From 3ec013b210963adae0489cad7adf55df9692ddfd Mon Sep 17 00:00:00 2001 From: Ben Klein Date: Sat, 10 Jul 2021 15:25:09 -0400 Subject: [PATCH] client/lua: handle the api server being offline --- client/metatags.lua | 48 ++++++++++++++++++++++++---------------- client/nginx.conf.docker | 1 + 2 files changed, 30 insertions(+), 19 deletions(-) diff --git a/client/metatags.lua b/client/metatags.lua index 1882f654..a227e247 100644 --- a/client/metatags.lua +++ b/client/metatags.lua @@ -1,21 +1,35 @@ +-- Set the response content type back to HTML +ngx.header.content_type = 'text/html'; + 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") -local server_info = cjson.decode((ngx.location.capture("/_internal_api/info")).body) - --- local document = gumbo.parse(page_html.body) --- --- function add_meta_tag (property, content) --- local new_element = document:createElement("meta") --- document.head:appendChild(new_element) --- new_element:setAttribute("property", property) --- new_element:setAttribute("content", content) --- end +local server_info_resp = ngx.location.capture("/_internal_api/info") +if server_info_resp.status ~= 200 then + 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) + return +end +local server_info = cjson.decode(server_info_resp.body) local additional_tags = "" - local function add_meta_tag (property, content) additional_tags = additional_tags .. "" end @@ -35,10 +49,6 @@ if ngx.var.request_uri_path:match('^/post') then end end -local final_response = page_html.body:gsub("{{ generated_head_tags }}", additional_tags) - --- Set the content type back to HTML -ngx.header.content_type = 'text/html'; - --- ngx.say(page_html.body) -ngx.say(final_response) +-- Once tags have been generated, write them and then finish the response +ngx.print(additional_tags) +ngx.print(after_content) diff --git a/client/nginx.conf.docker b/client/nginx.conf.docker index c5b2ada4..4f36a8b2 100644 --- a/client/nginx.conf.docker +++ b/client/nginx.conf.docker @@ -31,6 +31,7 @@ http { init_by_lua_block { cjson = require("cjson") + html_head_tag_replacement_str = "{{ generated_head_tags }}" } server {