How to serve static files in Julia?

Viewed 261

I am trying to build a small server similar to Flask and want to serve static files from it. My first thought was that Genie.jl could do this but I don't see anything about serving static files explicitly mentioned (unless I missed it).

2 Answers

You can simply place static file in the public folder of a created Genie app. If you have a peek at this folder you will even notice that Genie automatically places there standard web page files such as favicon.ico or robots.txt.

Consider the following Julia session:

julia> using Genie
julia> Genie.newapp("Demo1")
...

Ready!

ā”Œ Info: 2021-10-24 02:56:09
ā”” Web Server starting at http://127.0.0.1:8000

When being started Genie automatically changed location to the web app folder (here Demo1).

Let us create a sample static file in the Demo1/public folder:

open("public/static_sample.txt","w") do f;println(f,"Hello world!");end

Now we are ready to test the mechanism. Here I use curl tool being run from Julia, but you could simply copy-paste the url to a web browser:

julia> run(`curl http://127.0.0.1:8000/static_sample.txt`)
Hello world!
Process(`curl http://127.0.0.1:8000/static_sample.txt`, ProcessExited(0))

The simplest way to use Genie for serving static files is to use Genie.serve as documented here: https://genieframework.github.io/Genie.jl/dev/API/genie.html#Genie.serve

julia> Genie.serve("public", 8888, async = false, verbose = true)
[ Info: Ready!
[ Info: Listening on: 127.0.0.1:8888

Out of the box it will serve the requested file if it exists, it will return a 404 error page if it does not exist, and will look for an index.html file to serve by default if the path is a directory.

It does not list the files in the directory - though we could add it if useful, as an option.

Related