Skip to content

File and Resource Directives

Mathias edited this page Jul 27, 2011 · 4 revisions

Many web services also need to serve a small number of static files, e.g. for documentation purposes. spray makes this easy by defining a few directives that server content from the file system:

  • getFromFileName
  • getFromFile
  • getFromResource
  • getFromDirectory
  • getFromResourceDirectory

getFromFileName, getFromFile and getFromResource respond to GET requests with the contents of a given file or (JAR) resource, e.g.:

path("api" / "documentation") {
  getFromFile("/var/www/fancy-service/doc.html")
}

The -directory variants serve up whole directories. The following route for example

path("api" / "documentation") {
  getFromDirectory("/var/www/fancy-service/documentation/")
}

will respond to GET requests to /api/documentation/chapter/1.html with the contents of the file /var/www/fancy-service/documentation/chapter/1.html.

In order to allow for some more URI flexibility you can also supply getFromDirectory and getFromResourceDirectory with a "path rewriter" function argument String => String, which allows for custom preprocessing of the relevant path segment, before it is passed on to the file system. You might for example use it to append ".html" extensions for files that don't have one.

The getFrom... directives automatically set the content type of the HTTP response to the media type matching the file extension. For example ".html" files will be served with Content-Type: text/html while ".txt" files will receive a Content-Type: text/plain. You can also very easily supply your own media-types and/or file extensions. See the Custom Media Types chapter for further documentation on this.

Clone this wiki locally