-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.pl
90 lines (73 loc) · 2.52 KB
/
server.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/* Prolog Blog
* A Prolog application to run http://prologblog.com
*
* Copyright 2009 Jeff Dallien
* http://jeff.dallien.net/
* */
:- ['psp_templating'].
:- use_module(library('http/thread_httpd')).
:- use_module(library('http/http_dispatch')).
:- use_module(library('http/html_write')).
:- use_module(library('http/http_parameters')).
:- dynamic post/4.
:- multifile post/4.
server(Port) :-
http_server(http_dispatch, [port(Port)]).
:- http_handler('/', index_page, []).
:- http_handler('/post', single_post, []).
:- http_handler('/posts.rss', posts_rss, []).
:- http_handler('/request', request, []).
css(URL) -->
html(link([ type('text/css'),
rel('stylesheet'),
href(URL)
])).
% TODO: shouldn't need to do this on every request
setup_templating :-
nb_setval(psp_headers, not_required),
nb_setval(psp_error, no).
posts_rss(_Request) :-
setup_templating,
format('Content-type: text/xml~n~n', []),
format('<?xml version="1.0" encoding="UTF-8"?>', []),
run_page('views/posts.rss.prolog', []).
index_page(_Request) :-
setup_templating,
format('Content-type: text/html~n~n', []),!,
run_page('views/posts.html.prolog', []).
single_post(Request) :-
http_parameters(Request, [id(Id, [optional(true)])]),
atom_number(Id, PostId),
post(PostId, Title, Date, Body),
setup_templating,
format('Content-type: text/html~n~n', []),!,
run_page('views/post.html.prolog', ['Title'=Title, 'Id'=PostId, 'Date'=Date, 'Body'=Body]).
single_post(Request) :-
index_page(Request).
post(1, 'Congratulations', '16 March 2009', '<p>You have correctly set up a Prolog Blog server.</p>').
% can use this to force closing p tags
% p(X) --> ['<p>'], X, ['</p>'].
/* show the incoming request as a page */
request(Request) :-
format('Content-type: text/html~n~n', []),
format('<html><body>~n', []),
format('<pre>', []),
http_parameters(Request, [id(Id, [optional(true)])]),
write(Request),
write(Id),
format('</pre></body></html>').
escape_html_tags(Text, Escaped) :-
atom_codes(Text, Codes),
replace(60, "<", Codes, Escaped1),
replace(62, ">", Escaped1, Escaped2),
flatten(Escaped2, EscapedCodes),
atom_codes(Escaped, EscapedCodes).
post_escaped(A,B,C,EscapedBody) :-
post(A,B,C,Body),
escape_html_tags(Body,EscapedBody), !.
replace(_,_,[],[]).
replace(HReplacant,HReplacer,[HReplacant|Tail],[HReplacer|NewTail]):-
replace(HReplacant,HReplacer,Tail,NewTail).
replace(HReplacant,HReplacer,[Head|Tail],[Head|NewTail]):-
replace(HReplacant,HReplacer,Tail,NewTail).