StaticFileServer middleware. This guide will show you how to configure and register a static file server on your Kitura server.
If you don't have a Kitura server, follow our Create a server guide.
The first thing we are going to need is a static file to serve. By default the static file server looks in the "public" directory, so let's create that now.
From the root directory of your project, where
Package.swift is located, create the public directory:
Change into the directory:
Create a new file called
Open this file in your preferred text editor (we will use Xcode):
open hello.html -a Xcode.app
Inside this file, add the following text:
<!DOCTYPE html> <html> <body> <h1>Hello World!</h1> </body> </html>
In this example, we will serve an HTML file, however, this could be any file type.
If you are using Xcode and used the command line to create your public directory you will need to regenerate your Xcode project:
swift package generate-xcodeproj
This is to enable Xcode to detect the new directory.
StaticFileServer middleware is built into Kitura. To use it we just need register it on our router.
Application.swift file in your default text editor (or Xcode if you prefer):
postInit() function add:
router.all("/public", middleware: StaticFileServer())
That's it! Now, we will serve any files from the project's
public directory (since this is the default path) from the
/public route on our server.
We are using public for both the route and directory, however these could be set to anything.
For example, if you wanted to serve files from the
assets folder from the '/internal' route, you could use the following code:
router.all("/internal", middleware: StaticFileServer(path: "./assets"))
To test our static file server, we can view the HTML file we created earlier.
We do this by running our server, then opening our browser at:
We should see our HTML document with the "Hello World!" message.
StaticFileServer also loads files from subdirectories of the project's
public directory, so all we need to do is place a file into a subdirectory e.g.
./public/images/picture.png and it will be served at localhost:8080/public/picture.png.
Stencil: Learn how to add Stencil templating to your Kitura application.
Markdown: Learn how to add Markdown templating to your Kitura application.