gpt4 book ai didi

ruby-on-rails - Rails 可以像 Phoenix 管道一样为指定路由指定中间件

转载 作者:行者123 更新时间:2023-12-04 20:07:08 24 4
gpt4 key购买 nike

phoenix framework使用管道,我们可以为某些路由启用指定中间件,例如:

defmodule HelloPhoenix.Router do
use HelloPhoenix.Web, :router

pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_flash
plug :protect_from_forgery
plug :put_secure_browser_headers
end

pipeline :api do
plug :accepts, ["json"]
end

scope "/", HelloPhoenix do
pipe_through :browser # Use the default browser stack

get "/", PageController, :index
end

scope "/api", HelloPhoenix do
pipe_through :api
end
end

如果来自 /api 的请求, 只会触发 plug :accepts, ["json"]中间件

如果来自 / 的请求, 会触发 session, flash, ...等中间件

如果我使用 grape,如何在 Rails 上实现这一点用于构建 api 和 rails 用于构建网页并为彼此启用不同的中间件?

最佳答案

与 Phoenix 应用程序不同,您不能(轻松)更改 Rails 中用于请求的中间件。在 Rails 应用程序中获得这种行为的最佳方式是让特定路由的 Controller 继承自一个公共(public)基础 Controller ,然后在该基础 Controller 中定义这些特定 Controller 的行为。

使用上面的示例 /api路由通过不同的“中间件”,你可以有一个这样的 Controller :

module API
class BaseController < ActionController::API
# things unique to API routes go here
end
end

在这个 Controller 里面,你可以写一些 before_action确保以下内容的回调:
  • 入站请求仅为 JSON
  • 请求使用特定 token
  • 进行身份验证

    然后你可以从这个 Controller 继承所有 API Controller :
    module API
    class PostsController < API::BaseController
    end
    end

    使用常规 Controller ,您可以执行所有常规操作:
    class ApplicationController < ActionController::Base
    # things unique to non-api routes go here
    end

    进而:
    class PostsController < ApplicationController
    end

    您当然可以对其进行更多分割;也许您可能有另一条路线,例如 /accounts/1/posts您必须作为该帐户的用户进行身份验证才能查看帖子。您可以采用相同的方法:
    module Accounts
    class BaseController < ActionController::Base
    # find account, check if the user is authenticated, etc.
    end
    end

    和:
    module Accounts
    class PostsController < Accounts::BaseController
    end
    end

    总而言之:Rails 不允许您在路由级别(轻松地)执行此操作,但您可以在 Controller 级别完成相同的操作。

    关于ruby-on-rails - Rails 可以像 Phoenix 管道一样为指定路由指定中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45047760/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com