kif
Creating routes from a file
I’m trying to migrate a website to Phoenix. I have a JSON file with routes definitions.
How can I route traffic base on my file definitions?
I fond this post but it only adds more questions.
Most Liked
rogerweb
I’m pretty sure if you create your own plug it would be more elegant, but you can read your json file from within your endpoint.ex, iterate over the routes and add a Plug.Static for each.
I did a simple POC just to show you what can be done:
for route <- ["aaa", "bbb", "ccc"] do
plug Plug.Static,
at: "/" <> route, # the path as in the browser
from: "/home/roger/code/temp/hello/" <> route, # the path in the filesystem
gzip: false
end
Provided you have an index.html file in /home/roger/code/temp/hello/aaa/, you can access it from http://localhost:4000/aaa/index.html. The path in the filesystem doesn’t need to be directly related to the path in the URL, it was just an example. I would take a look at the documentation of Plug.Static to check all the options.
rogerweb
Considering you have content, meta-data, route and status, it looks we are talking about a CMS here, isn’t it?
If that’s not the case, if your your site is static then you may read the file from a one-time script (elixir or not) that simply organizes the content files in a directory structure that can then be served statically, by Plug.Static or even an external webserver like nginx.
If you really want to create Phoenix routes dynamically, you could read the JSON content from your config.exs file and have is as a compilation-time list that you can iterate over from your routes.ex file to dynamically create the routes. Of course if you change the JSON then you would have to re-compile your application.
Last, you could have a dynamic website with a single route with a parameter in the URL path that you use to match against a keyword (for instance, “vertex-cache”). With the keyword, you would fetch data from a database or from an in-memory structure with the contents of your JSON to serve the correct content.
kif
I didn’t know that you can add plugs in a for loop like this! Also following your suggestion I’m trying to see if I can make my custom plug that I can modify static path dynamically. Still struggling but thanks for this direction! Need some time to process this information.







