diff mod_rest/mod_rest.lua @ 4037:991090cb5d18

mod_rest: Add support for CBOR https://www.zash.se/lua-cbor.html
author Kim Alvefur <zash@zash.se>
date Fri, 29 May 2020 12:38:23 +0200
parents 04c11b652aeb
children 07ae583bc565
line wrap: on
line diff
--- a/mod_rest/mod_rest.lua	Fri May 29 12:30:15 2020 +0200
+++ b/mod_rest/mod_rest.lua	Fri May 29 12:38:23 2020 +0200
@@ -14,6 +14,7 @@
 local st = require "util.stanza";
 local um = require "core.usermanager";
 local xml = require "util.xml";
+local have_cbor, cbor = pcall(require, "cbor");
 
 local jsonmap = module:require"jsonmap";
 
@@ -68,6 +69,12 @@
 			return parsed, err;
 		end
 		return jsonmap.json2st(parsed);
+	elseif mimetype == "application/cbor" and have_cbor then
+		local parsed, err = cbor.decode(data);
+		if not parsed then
+			return parsed, err;
+		end
+		return jsonmap.json2st(parsed);
 	elseif mimetype == "application/x-www-form-urlencoded"then
 		local parsed = http.formdecode(data);
 		if type(parsed) == "string" then
@@ -106,9 +113,16 @@
 	"application/json",
 };
 
+if have_cbor then
+	table.insert(supported_inputs, "application/cbor");
+	table.insert(supported_outputs, "application/cbor");
+end
+
 local function encode(type, s)
 	if type == "application/json" then
 		return json.encode(jsonmap.st2json(s));
+	elseif type == "application/cbor" then
+		return cbor.encode(jsonmap.st2json(s));
 	elseif type == "text/plain" then
 		return s:get_child_text("body") or "";
 	end