I need to implement a directory listing similar to the one the Apache server has.
There is a root directory, which is served by default. If a directory is requested, the server responds with the links to the files within the corresponding directory. If a file is requested, the server responds with the file's contents and the appropriate MIME type.
The Ktor's static content serving functionality does not cover my use case.
The directory listing can be implemented by defining a tail card route where the requested path can be used for determining the path to the corresponding directory or the file.
The requested path can be retrieved using the name of the tail card parameter by accessing the
call.parametersproperty. TheApplicationCall.respondFilemethod can be used to respond with the file contents. The directory contents can be listed using theArray<File>.listFilesmethod and then rendered to an HTML string.Here is an example implementation:
An example usage: