-
Notifications
You must be signed in to change notification settings - Fork 0
/
japp_static_resource.erl
64 lines (54 loc) · 2.19 KB
/
japp_static_resource.erl
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
%% @author author <[email protected]>
%% @copyright Daniel Kwiecinski.
%% @doc Static webmachine resource.
-module(static_{{appid}}_resource).
-export([init/1, allowed_methods/2,
content_types_provided/2, resource_exists/2, last_modified/2, provide_content/2]).
-include_lib("webmachine/include/webmachine.hrl").
-include_lib("kernel/include/file.hrl").
-record(context, {docroot,fullpath,fileinfo}).
init(DocRoot) ->
Directory = filename:join([code:priv_dir({{appid}}),"..", "..", "..",DocRoot]),
{ok, #context{docroot=Directory}}.
resource_exists(ReqData, Context) ->
%%lager:info("2.... ~p", [wrq:disp_path(ReqData)]),
case get_full_path(Context#context.docroot, wrq:disp_path(ReqData)) of
undefined -> {false, ReqData, Context};
Path ->
case filelib:is_regular(Path) of
true ->
case file:read_file_info(Path) of
{ok, FileInfo} -> {true, ReqData, Context#context{fileinfo=FileInfo}};
{error, _} -> {false, ReqData, Context}
end;
_ -> {false, ReqData, Context}
end
end.
content_types_provided(ReqData, Context) ->
Path = get_full_path(Context#context.docroot, wrq:disp_path(ReqData)),
{[{webmachine_util:guess_mime(Path), provide_content}], ReqData, Context#context{fullpath=Path}}.
allowed_methods(ReqData, Context) -> {['HEAD', 'GET'], ReqData, Context}.
last_modified(ReqData, Context) ->
{(Context#context.fileinfo)#file_info.mtime, ReqData, Context}.
provide_content(ReqData, Context) ->
{ok, Value} = file:read_file(Context#context.fullpath),
{Value, ReqData, Context}.
% ------------------ PRIVATE ------------------------
get_full_path(DocRoot, Path) ->
case mochiweb_util:safe_relative_path(Path) of
undefined -> undefined;
RelPath ->
FullPath = filename:join([DocRoot, RelPath]),
case filelib:is_dir(FullPath) of
true ->
filename:join([FullPath, "index.html"]);
false ->
FullPath
end
end.
%% --------------------------------------------------------------------
%%% Test functions
%% --------------------------------------------------------------------
-include_lib("eunit/include/eunit.hrl").
-ifdef(TEST).
-endif.