Skip to content

Commit

Permalink
add AssetMiddleware for react-router routing priority
Browse files Browse the repository at this point in the history
  • Loading branch information
letsspeak committed Feb 2, 2018
1 parent 68adc2d commit 73ea773
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 0 deletions.
1 change: 1 addition & 0 deletions Config/droplet.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
"xfp-middleware",
"error",
"date",
"asset-middleware",
"file"
],

Expand Down
38 changes: 38 additions & 0 deletions Sources/App/Middleware/AssetMidleware.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import Foundation
import HTTP
import libc

/// Servers files from the supplied public directory
/// on not found errors.
public final class AssetMiddleware: Middleware {

private var assetDirs: [String]
private var publicDir: String

private let loader = DataFile()
private let chunkSize: Int

public init(assetDirs: [String], publicDir: String, chunkSize: Int? = nil) {
// Remove last "/" from the publicDir if present, so we can directly append uri path from the request.
self.assetDirs = assetDirs
self.publicDir = publicDir.finished(with: "/")
self.chunkSize = chunkSize ?? 32_768 // 2^15
}

public func respond(to request: Request, chainingTo next: Responder) throws -> Response {
var path = request.uri.path
guard !path.contains("../") else {
throw HTTP.Status.forbidden
}
if path.hasPrefix("/") {
path = String(path.dropFirst())
}
if assetDirs.index(where: { path.starts(with: $0) }) != nil {
let filePath = publicDir + path
let ifNoneMatch = request.headers["If-None-Match"]
return try Response(filePath: filePath, ifNoneMatch: ifNoneMatch, chunkSize: chunkSize)
}
return try next.respond(to: request)
}
}

9 changes: 9 additions & 0 deletions Sources/Run/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,18 @@ import XFPMiddleware
/// if no command is given, it will default to "serve"
let config = try Config()
try config.setup()

let xfpMiddleware = XFPMiddleware()
config.addConfigurable(middleware: xfpMiddleware, name: "xfp-middleware")

let assetDirs = [
"js/",
"images/",
]

let assetMiddleware = AssetMiddleware(assetDirs: assetDirs, publicDir: config.publicDir)
config.addConfigurable(middleware: assetMiddleware, name: "asset-middleware")

let drop = try Droplet(config)
try drop.setup()

Expand Down

0 comments on commit 73ea773

Please sign in to comment.