Packages
raxx
0.17.4
1.1.0
1.0.1
1.0.0
1.0.0-rc.3
1.0.0-rc.2
retired
1.0.0-rc.1
retired
1.0.0-rc.0
retired
0.18.1
0.18.0
0.17.6
0.17.5
0.17.4
0.17.3
0.17.2
0.17.1
0.17.0
0.16.1
0.16.0
retired
0.15.11
0.15.10
0.15.9
0.15.8
0.15.7
0.15.6
0.15.5
0.15.4
0.15.3
0.15.2
0.15.1
0.15.0
0.14.14
0.14.13
0.14.12
0.14.11
0.14.10
0.14.9
0.14.8
0.14.7
0.14.6
0.14.5
0.14.4
0.14.3
0.14.2
0.14.1
0.14.0
0.13.0
0.12.3
0.12.2
0.12.1
0.12.0
0.11.1
0.11.0
0.10.5
0.10.4
0.10.3
0.10.2
0.10.1
0.10.0
0.9.0
0.8.2
0.8.1
0.8.0
0.7.1
0.7.0
0.6.0
0.5.2
0.5.1
0.5.0
0.4.3
0.4.2
0.4.1
0.4.0
0.3.0
0.2.0
0.1.0
0.0.1
Interface for HTTP webservers, frameworks and clients.
Current section
Files
Jump to
Current section
Files
lib/raxx/request_id.ex
defmodule Raxx.RequestID do
@moduledoc """
Generate a unique identifier for a request.
An invalid id, sent as `x-request-id`, will be overwritten if it is invalid.
A valid id is any string between 20 and 200 charachters
The request id is added to the Logger metadata as `:request_id`.
To see the request id in your log output, configure your logger backends to include the `:request_id` metadata:
To use this middleware just use it in any Raxx.Server module.
use Raxx.RequestID
"""
@header_name "x-request-id"
defmacro __using__(_options) do
quote do
@before_compile unquote(__MODULE__)
end
end
defmacro __before_compile__(__env) do
quote do
defoverridable Raxx.Server
@impl Raxx.Server
def handle_head(head, config) do
{id, head} = unquote(__MODULE__).ensure_request_id(head)
Logger.metadata(request_id: id)
super(head, config)
end
end
end
@doc """
Fetch the id of a request or generate new value
## Examples
iex> request(:GET, "/")
...> |> set_header("x-request-id", "12345678901234567890")
...> |> ensure_request_id()
...> |> elem(0)
"12345678901234567890"
"""
def ensure_request_id(head) do
case Raxx.get_header(head, @header_name) do
nil ->
id = generate_request_id()
head = Raxx.set_header(head, @header_name, id)
{id, head}
invalid_id when byte_size(invalid_id) < 20 or byte_size(invalid_id) > 200 ->
id = generate_request_id()
head =
head
|> Raxx.delete_header(@header_name)
|> Raxx.set_header(@header_name, id)
{id, head}
id ->
{id, head}
end
end
defp generate_request_id do
binary = <<
System.system_time(:nanoseconds)::64,
:erlang.phash2({node(), self()}, 16_777_216)::24,
:erlang.unique_integer()::32
>>
Base.hex_encode32(binary, case: :lower)
end
end