Skip to content

Commit 64087f6

Browse files
authored
Add assign_as option for Plug.RequestId (#1172)
- `:assign_as` - The name of the key that will be used to store the discovered or generated request id in `conn.private`. If not provided, the request id will not be stored. ```elixir plug Plug.RequestId, assign_as: :plug_request_id ``` Resolves: #1171
1 parent 8f1bf1c commit 64087f6

File tree

2 files changed

+33
-5
lines changed

2 files changed

+33
-5
lines changed

lib/plug/request_id.ex

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,12 @@ defmodule Plug.RequestId do
3434
3535
plug Plug.RequestId, http_header: "custom-request-id"
3636
37+
* `:assign_as` - The name of the key that will be used to store the
38+
discovered or generated request id in `conn.assigns`. If not provided,
39+
the request id will not be stored.
40+
41+
plug Plug.RequestId, assign_as: :plug_request_id
42+
3743
"""
3844

3945
require Logger
@@ -42,14 +48,17 @@ defmodule Plug.RequestId do
4248

4349
@impl true
4450
def init(opts) do
45-
Keyword.get(opts, :http_header, "x-request-id")
51+
{
52+
Keyword.get(opts, :http_header, "x-request-id"),
53+
Keyword.get(opts, :assign_as)
54+
}
4655
end
4756

4857
@impl true
49-
def call(conn, req_id_header) do
58+
def call(conn, {header, assign_as}) do
5059
conn
51-
|> get_request_id(req_id_header)
52-
|> set_request_id(req_id_header)
60+
|> get_request_id(header)
61+
|> set_request_id(header, assign_as)
5362
end
5463

5564
defp get_request_id(conn, header) do
@@ -59,8 +68,11 @@ defmodule Plug.RequestId do
5968
end
6069
end
6170

62-
defp set_request_id({conn, request_id}, header) do
71+
defp set_request_id({conn, request_id}, header, assign_as) do
6372
Logger.metadata(request_id: request_id)
73+
74+
conn = if assign_as, do: Conn.assign(conn, assign_as, request_id), else: conn
75+
6476
Conn.put_resp_header(conn, header, request_id)
6577
end
6678

test/plug/request_id_test.exs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,22 @@ defmodule Plug.RequestIdTest do
6565
assert res_request_id == meta_request_id
6666
end
6767

68+
test "assigns the request id to conn.assigns when given an assignment key" do
69+
request_id = "existingidthatislongenough"
70+
71+
conn =
72+
conn(:get, "/")
73+
|> put_req_header("x-request-id", request_id)
74+
|> call(assign_as: :plug_request_id)
75+
76+
[res_request_id] = get_resp_header(conn, "x-request-id")
77+
meta_request_id = Logger.metadata()[:request_id]
78+
assigned_request_id = conn.assigns.plug_request_id
79+
assert assigned_request_id == request_id
80+
assert res_request_id == assigned_request_id
81+
assert res_request_id == meta_request_id
82+
end
83+
6884
defp generated_request_id?(request_id) do
6985
Regex.match?(~r/\A[A-Za-z0-9-_]+\z/, request_id)
7086
end

0 commit comments

Comments
 (0)