【问题标题】:Phoenix framework pattern match request headersPhoenix 框架模式匹配请求标头
【发布时间】:2017-02-21 17:23:22
【问题描述】:

我正在尝试为 API 版本控制实现自定义插件。现在我需要能够匹配通过请求标头传递的值(即Accept: application/vnd.app.v1+json)。到目前为止,我已经实现了以下内容:

defmodule UsersApi.Plugs.APIVersion do
  import Plug.Conn

  @versions ["application/vnd.app.v1+json", "application/vnd.app.v2+json"]

  def init(version), do: version

  def call(%{req_headers: %{"accept" => version}} = conn, _) when version in @versions do
    assign(conn, :version, version)
  end

  def call(conn, version), do: assign(conn, :version, version)
end

这目前无法正常工作,并且一直到第二个call/2,该call/2 被设计为未指定接受标头时的后备。如何匹配请求头?

【问题讨论】:

  • req_headers 是一个列表;你不能像这样进行模式匹配。不过你可以使用get_req_header/2

标签: elixir phoenix-framework plug


【解决方案1】:

req_headers 是一个列表,但您像地图一样对其进行模式匹配,这总是失败,并且所有对 call/2 的调用都以后备方式结束。您可以为此使用get_req_header/2

def call(conn, default_version) do
  version = case get_req_header(conn, "accept") do
    [version] when version in @versions -> version
    _ -> default_version
  end
  assign(conn, :version, version)
end

【讨论】:

  • 这是完美的。谢谢!!
  • 守卫中的模式匹配怎么样?这不能做,可以吗?
猜你喜欢
  • 1970-01-01
  • 2017-03-16
  • 1970-01-01
  • 1970-01-01
  • 2014-12-07
  • 2021-02-03
  • 1970-01-01
  • 2016-05-26
  • 1970-01-01
相关资源
最近更新 更多