Ankit Goel
Ankit Goel

Reputation: 6495

How do I write a middleware for vapor web framework?

Created a new project using toolbox command: vapor new projectname

In main.swift file I added the middleware code:

import Vapor
import HTTP

final class VersionMiddleware: Middleware {
    func respond(to request: Request, chainingTo next: Responder) throws -> Response {
        let response = try next.respond(to: request)

        response.headers["Version"] = "API v1.0"
        print("not printing")

        return response
    }
}

let drop = Droplet(availableMiddleware: [
    "version": VersionMiddleware()
])

drop.get("hello") {
    req in 
    return "Hello world"
} 

drop.run()

But when I run this, it prints "hello world" but the API version is not added to headers. I am checking it using postman.

Upvotes: 3

Views: 1111

Answers (2)

marc-medley
marc-medley

Reputation: 9832

Vapor 1 ➙ 2 Migration Note: "middleware" ordering configuration has moved from Config/middleware.json to Config/droplet.json.

Vapor 2

In Vapor 2, middleware can be created, added, and configured as follows:

Sources/App/Middleware/ExampleMiddleware.swift

final class ExampleMiddleware: Middleware {
  func respond(to request: Request, chainingTo next: Responder) throws -> Response {
    // if needed, process inbound `request` here.
    // Swift.print(request.description)

    // pass next inbound `request` to next middleware in processing chain
    let response: Response = try next.respond(to: request)

    // if needed, process outbound `response` here
    // Swift.print(response.description)

    // return `response` to chain back up any remaining middleware to client
    return response
  }
}

Sources/App/Setup/Config+Setup.swift

extension Config {
  public func setup() throws {
    …
    try setupMiddleware()
    …
  }

  public func setupMiddleware() throws {
    self.addConfigurable(
        middleware: ExampleMiddleware(), 
        name: "example" 
    )     
  }
}

Config/droplet.json

"middleware": [
    …,
    "example"
],

Note: Middleware directly included in Vapor 2 (such as "error", "sessions", "file", "date", "cors") would be used in Config/droplet.json "middleware" without the addConfigurable(middleware, name) setup step.

Vapor 2 Docs: Middleware ⇗

Upvotes: 2

wei chen
wei chen

Reputation: 91

I think you should configure Config/middleware.json

{
"server": [
    ...
    "version"
],
...
}

It will be work.

middleware document

Upvotes: 2

Related Questions