dream/controllers/static

Secure static file serving

Serve files from disk with built-in security. Handles CSS, JavaScript, images, and any other static assets your application needs.

Quick Setup

import dream/controllers/static
import dream/http/transaction.{get_string_param}

pub fn serve_assets(request, ctx, svc) {
  case get_string_param(request, "path") {
    Ok(path) -> static.serve(
      request: request,
      context: ctx,
      services: svc,
      root: "./public",
      filepath: path,
      config: static.default_config(),
    )
    Error(msg) -> json_response(status.bad_request, error_json(msg))
  }
}

// In your router:
router.route(Get, "/assets/**path", serve_assets, [])

Security

Built-in protection against:

Files outside the root directory return 404, never errors that reveal filesystem structure.

Features

Types

Configuration for static file serving

pub type Config(context, services) {
  Config(
    serve_index: Bool,
    allow_directory_listing: Bool,
    not_found_handler: option.Option(
      fn(request.Request, context, services) -> response.Response,
    ),
  )
}

Constructors

  • Config(
      serve_index: Bool,
      allow_directory_listing: Bool,
      not_found_handler: option.Option(
        fn(request.Request, context, services) -> response.Response,
      ),
    )

    Arguments

    serve_index

    Whether to serve index.html for directory requests

    allow_directory_listing

    Whether to allow directory listing when no index.html exists

    not_found_handler

    Custom 404 handler (None = default 404 response)

Values

pub fn default_config() -> Config(context, services)

Default configuration with secure settings

pub fn serve(
  request request: request.Request,
  context context: context,
  services services: services,
  root root: String,
  filepath filepath: String,
  config config: Config(context, services),
) -> response.Response

Serve static files from a directory

Security:

  • Prevents path traversal attacks (../)
  • Validates paths stay within root directory
  • Returns 404 for files outside root

Usage:

pub fn serve_public(request: Request, ctx, svc) -> Response {
  case get_string_param(request, "filepath") {
    Ok(filepath) -> static.serve(
      request: request,
      context: ctx,
      services: svc,
      root: "./public",
      filepath: filepath,
      config: static.default_config(),
    )
    Error(msg) -> json_response(status.bad_request, error_json(msg))
  }
}
pub fn with_custom_404(
  config: Config(context, services),
  handler: fn(request.Request, context, services) -> response.Response,
) -> Config(context, services)

Set custom 404 handler

pub fn with_directory_listing(
  config: Config(context, services),
) -> Config(context, services)

Enable directory listing

pub fn without_index(
  config: Config(context, services),
) -> Config(context, services)

Disable automatic index.html serving

Search Document