Arm1.ru

A middleware for Vapor 4 routing to trim a slash in url path

It’s a common thing for a website or a backend to allow URLs like mySite.com/webpage and mySite.Com/webpage/ for the same page. These pages are different URLs for a search engine. If you want to avoid duplicates, you can add a simple middleware to trim the ending slash and redirect a user.

Here’s an example code for such a middleware class for Vapor 4:

final class TrimSlashInPathMiddleware: Middleware {
    func respond(to request: Request, chainingTo next: Responder) -> EventLoopFuture<Response> {
        if request.url.path.count > 1, request.url.path.hasSuffix("/") {
            let newPath = String(request.url.path.trimmingSuffix(while: { $0 == "/" }))
            let response = request.redirect(to: newPath, redirectType: .permanent)
            return request.eventLoop.makeSucceededFuture(response)
        }
        return next.respond(to: request)
    }
}

Just add it to configure.swift file:

import Vapor

public func configure(_ app: Application) throws {
    app.middleware.use(TrimSlashInPathMiddleware())

    app.http.server.configuration.port = 8081

    try routes(app)
}

Works with Vapor 4.92.5.

keyboard_return back