9:- module(sw_route_handling,
10 [ init_routes/0
11 , url_for/2
12 , url_for/3
13 ]
14). 15
16:- use_module(library(http/thread_httpd)). 17:- use_module(library(http/http_dispatch)). 18:- use_module(library(http/http_path)).
24init_routes :-
25 findall(N-R, clause(sw:route(N, R, _Request), _), RoutesS),
26 findall(N-R-M, clause(sw:route(N, R, M, _Req), _), RoutesM),
27 append(RoutesS, RoutesM, Routes),
28 handle_routes(Routes).
35handle_routes([]).
36handle_routes([R| Routes]) :-
37 handle_route(R),
38 handle_routes(Routes).
44handle_route(N-R-M) :-
45 log_route(N, R),
46 http_handler( R,
47 method_route(N, R, M),
48 []).
49handle_route(N-R) :-
50 \+ R = _-_,
51 \+ N = _-_,
52 ground(R),
53 log_route(N, R),
54 http_handler( R,
55 sw:route(N, R),
56 []).
57handle_route(N-R) :-
58 \+ R = _-_,
59 \+ N = _-_,
60 \+ ground(R),
61 log_route(N, R),
62 R =.. [P|_],
63 Route =.. [P, '.'],
64 http_handler( Route,
65 var_route(N, P),
66 [prefix]).
70log_route(Name, Route) :-
71 asserta(sw:handler_url(Name, Route)).
73log_route(Name, Route, Method) :-
74 asserta(sw:handler_url(Name, Route, Method)).
84url_for("static", "/static").
85url_for(StaticPath, URL) :-
86 term_string(static(Path), StaticPath),
87 string_concat("/static/", Path, URL).
88url_for(Handler, URL) :-
89 \+ string(Handler),
90 sw:handler_url(Handler, Route),
91 http_absolute_location(Route, URL, [relative_to(root)]).
92url_for(SHandler, URL) :-
93 string(SHandler), term_string(Handler, SHandler),
94 sw:handler_url(Handler, Route),
95 http_absolute_location(Route, URL, [relative_to(root)]).
96url_for(Handler, URL, []) :-
97 url_for(Handler, URL).
98url_for(Handler, URL, [absolute]) :-
99 ground(Handler),
100 sw:handler_url(Handler, Route),
101 http_absolute_uri(Route, URL).
111method_route(N, R, M, Request) :-
112 member(M, Request),
113 sw:route(N, R, M, Request), !.
114method_route(_, _, _, Request) :-
115 http_404([], Request).
120var_route(N, P, Request) :-
121 member(path_info(A), Request),
122 atomic_list_concat(Args, '/', A),
123 R =.. [P|Args],
124 sw:route(N, R, Request).
125var_route(_, _, Request) :-
126 http_404([], Request)
Route Handling
Make a route predicate in the project handle the route and write out the response to current out
*/