2017-02-14 7 views
3

私はVaporプロジェクトを作成しました。以下のように2つのビューと2つのAPIを登録しました。ミドルウェアからいくつかのビューを除外します。蒸気

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"; 
    } 

ミドルウェアコード:私の質問はあり

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

ユーザーは、それが検証する必要がありhome.htmlロードしようとするたびに

// 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." 
       ) 
      } 
     } 
    } 

は、ミドルウェアの設定を追加しましたミドルウェア cond私たちが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"; 
} 

をミドルウェアを割り当て、それが正常に動作しています

+0

addConfigurableメソッドを呼び出すことはありません!ありがとう –

+0

@Vignesh Kumarあなたはこの答えを正しいものとして受け入れるべきです。 –

関連する問題