2017-02-14 38 views
3

我已經創建了Vapor項目。我已經註冊了兩個視圖和兩個API,如下所示。從中間件排除一些視圖Vapor

drop.get { req in 
     return try drop.view.make("index.html") 
    } 

    drop.get("home") { req in 
     return try drop.view.make("home.html") 
    } 

    // Register the GET request routes 
    drop.get("appname") { request in 
     return "Welcome to Swift Web service"; 
    } 

    drop.get("appversion") { request in 
     return "v1.0"; 
    } 

中間件代碼:

// Added the Middleware version for request and response 
    final class VersionMiddleware: Middleware { 

     // Interact with request and response 
     func respond(to request: Request, chainingTo next: Responder) throws -> Response { 

      //Middleware is the perfect place to catch errors thrown from anywhere in the application. 
      do { 
       // Exclude the views from middleware 
       if (request.uri.path != "/") { 
        // The request has a 'Version' named token that equals "API \(httpVersion)" 
        guard request.headers["access_token"] == "\(publicAPIKey)" else { 
         throw Abort.custom(
          status: .badRequest, 
          message: "Sorry, Wrong web service authendication!!" 
         ) // The request will be aborted. 
        } 

       } 
       let response = try next.respond(to: request) 
       response.headers["Version"] = "API \(httpVersion)" 
       return response 
      } catch { 
       throw Abort.custom(
        status: .badRequest, 
        message: "Sorry, we were unable to query the Web service." 
       ) 
      } 
     } 
    } 

新增中間件配置:

// Configure the middleware 
    drop.addConfigurable(middleware: VersionMiddleware() as Middleware, name: "VersionMiddleware") 

我的問題是:

當用戶嘗試加載home.html的應該驗證中間件 cond itions和如果我們加載index.html服務器將排除 中間件驗證。

與API中的一樣:無論何時用戶嘗試加載「/ appname」,它應該驗證中間件條件,如果我們加載「appversion」服務器,則 將排除中間件驗證。

我已經使用request.uri.path!=「/」完成了此操作。我們有沒有其他方法可以在Vapor中進行配置?

回答

2

您可以group一組路線和指定中間件有

drop.group(VersionMiddleware()) { group in 
    drop.get("home") { req in 
     return try drop.view.make("home.html") 
    } 

    // Register the GET request routes 
    drop.get("appname") { request in 
     return "Welcome to Swift Web service"; 
    } 
} 

drop.get { req in 
    return try drop.view.make("index.html") 
} 

drop.get("appversion") { request in 
    return "v1.0"; 
} 

而且不叫addConfigurable方法

+0

它的正常工作!謝謝 –

+0

@Vignesh庫馬爾你應該接受這個答案是正確的。 –