I inherited some server code I don't fully understand and have been tasked with having it return JSON instead of plain strings. Here's what the current code looks like:
:- use_module(library(http/thread_httpd)).
:- use_module(library(http/http_dispatch)).
:- use_module(library(http/http_error)).
:- use_module(library(http/html_write)).
:- use_module(library(http/http_client)).
:- http_handler('/', web_form, []).
server(Port) :-
http_server(http_dispatch, [port(Port)]).
web_form(_Request) :-
reply_html_page(
title('POST demo'),
[
form([action='/', method='POST'],
[h1('Prolog Server')]
)
]
).
:- http_handler('/dataexchange', dataexchange_handler, [time_limit(infinite)]).
dataexchange_handler(Request) :-
member(method(post), Request), !,
http_read_data(Request, DataString, []),
general_predicate( DataString, OutString ),
format('Content-type: text/html~n~n', []),
portray_clause(OutString).
general_predicate( InString, Out ) :-
term_string( TotalTerm, InString ),
call_process_request( TotalTerm, ResultTerm ),
term_string( ResultTerm, Out ).
The 'portray_clause' seems a bit kooky, but the current functionality definitely works (returning strings). I can construct SWIPL json objects using ResultTerm, but am not entirely sure what to do with them subsequently.