markdown_converter.erl 751 B

1234567891011121314151617181920212223242526272829
  1. %% Feel free to use, reuse and abuse the code in this file.
  2. -module(markdown_converter).
  3. -behaviour(cowboy_middleware).
  4. -export([execute/2]).
  5. execute(Req, Env) ->
  6. {[Path], Req1} = cowboy_req:path_info(Req),
  7. case filename:extension(Path) of
  8. <<".html">> -> maybe_generate_markdown(resource_path(Path));
  9. _Ext -> ok
  10. end,
  11. {ok, Req1, Env}.
  12. maybe_generate_markdown(Path) ->
  13. ModifiedAt = filelib:last_modified(source_path(Path)),
  14. GeneratedAt = filelib:last_modified(Path),
  15. case ModifiedAt > GeneratedAt of
  16. true -> erlmarkdown:conv_file(source_path(Path), Path);
  17. false -> ok
  18. end.
  19. resource_path(Path) ->
  20. {ok, Cwd} = file:get_cwd(),
  21. filename:join([Cwd, "priv", Path]).
  22. source_path(Path) ->
  23. << (filename:rootname(Path))/binary, ".md" >>.