Using eWebmachine to create a link shortener (part 3)
Posted on October 12, 2014 by Clive in Elixir, eWebmachine, Mustache
In the last of these articles on the link shortener, I am going to discuss static assets. There are two ways of serving static assets - through a webserver like Apache (Apache Webserver) or using Webmachine.
We’ll add some simple static serving capability to the project. First off add the following directories to your project: assets/css into this new directory add bootstrap.min.css from (Bootstrap) and an empty file shorten.css. To the file templates/latest.html.mustache from the last post, add the following lines to the head section: Once these changes have been made, add a new file into the lib/ directory: ShortenerStaticResource The last thing that will need to happen is that the resource needs adding to the supervisor. Change the lib/shortener_supervisor.ex: Build and restart the project in the normal way: To test the page, you will need to add some content to the store. Then in a web browser, navigate to http://localhost:18080/latest. You should now see a rendered page. I am not vouching for the design, but this is easily cleaned up.$ mkdir -p assets/css
<link href="css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="css/shorten.css" rel="stylesheet" type="text/css" />
defmodule ShortenerStaticResource do
use Ewebmachine
resource ['css', :filename] do
resource_exists do
dispath = :wrq.path_info(:filename, _req)
filepath = "assets/css/#{dispath}"
case File.stat(filepath) do
{:ok, fileinfo} ->
case {fileinfo.type, fileinfo.access} do
{:regular, access} when access == :read or access == :read_write ->
pass filepath != nil, filepath: filepath
_ -> false
end
{:error, _} -> false
end
end
content_types_provided do
mime = :webmachine_util.guess_mime(:wrq.path(_req))
{[{mime, :provide_content}], _req, _ctx}
end
defp provide_content(_req, _ctx) do
{:ok, body} = File.read(_ctx[:filepath])
{body, _req, _ctx}
end
end
end
supervisor(Ewebmachine.Sup,[[modules: [ShortenerStaticResource, ShortenerLatestResource, ShortenerShortenResource, ShortenerFetchResource],port: 18080]]),
$ iex -S mix
ShortenUrlSrv.put_url("http://www.distortedthinking.agency")