bolt on support for simple JSON-returning services by EGWeb
authorGalen Charlton <gmc@equinoxinitiative.org>
Fri, 18 May 2018 18:34:16 +0000 (14:34 -0400)
committerGalen Charlton <gmc@equinoxinitiative.org>
Fri, 18 May 2018 21:32:06 +0000 (17:32 -0400)
This patch adds a way for EGWeb context loaders to specify that
a response should be emitted as JSON rather than rendering an HTML
page using Template::Toolkit.

Specifically, if the context as munged by the context loader contains
a json_response key, the contents of that key will to provide a
JSON reponse. The json_response_cookie key, if present, can be used
to set a cookie as part of the response.

Template Toolkit processing is bypassed entirely when emitting a JSON
response, so the context loader would be entirely reponsible for
localization of strings in the response meant for direct human
consumption.

Signed-off-by: Galen Charlton <gmc@equinoxinitiative.org>
Open-ILS/src/perlmods/lib/OpenILS/WWW/EGWeb.pm

index 8dc09cb..0d2fe26 100644 (file)
@@ -81,6 +81,19 @@ sub handler_guts {
         $stat = Apache2::Const::OK;
     }   
     return $stat unless $stat == Apache2::Const::OK;
+
+    # emit context as JSON if handler requests
+    if ($ctx->{json_response}) {
+        $r->content_type("application/json; charset=utf-8");
+        $r->headers_out->add("cache-control" => "no-store, no-cache, must-revalidate");
+        $r->headers_out->add("expires" => "-1");
+        if ($ctx->{json_reponse_cookie}) {
+            $r->headers_out->add('Set-Cookie' => $ctx->{json_reponse_cookie})
+        }
+        $r->print(OpenSRF::Utils::JSON->perl2JSON($ctx->{json_response}));
+        return Apache2::Const::OK;
+    }
+
     return Apache2::Const::DECLINED unless $template;
 
     my $text_handler = set_text_handler($ctx, $r);