2016-10-02 47 views
3

創建使用工具箱命令一個新項目:汽新項目名稱如何編寫一個蒸汽網頁框架的中間件?

在main.swift文件我加了中間件代碼:

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() 

但是當我運行它,它打印的「Hello World」,但API版本不添加到標題。我正在用郵差檢查它。

回答

2

我覺得你應該配置Config/middleware.json

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

這將是工作。

middleware document

1

蒸氣1➙2遷移注: 「中間件」 訂購配置已經從配置/ middleware.json移動到配置/ droplet.json

氣相2

在蒸氣2,可以創建中間件,添加,並且被配置如下:

源頭/應用/中間件/ 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 
    } 
} 

來源/應用/設置/配置+ Setup.swift

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

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

配置/ droplet.json

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

注:中間件直接包括在氣相2(如 「錯誤」, 「會話」, 「文件」, 「日期」,「CORS 「)將在Config/droplet.json"middleware"中使用,而不需要addConfigurable(middleware, name)設置步驟。

Vapor 2 Docs: Middleware ⇗