檢視原始碼 Phoenix.Digester.Compressor 行為 (Phoenix v1.7.14)

定義 Phoenix.Digester.Compressor 行為以實現靜態檔案壓縮器。

自訂壓縮器要求實作 2 個函式。

預設情況下,Phoenix 僅使用 Phoenix.Digester.Gzip 來壓縮靜態檔案,但可以定義並新增其他的壓縮器至摘要程序。

範例

如果你想要使用外部的 brotli 壓縮程式庫來壓縮檔案,你可以定義實作這個行為的新模組,並將此模組新增至已設定的 Phoenix 靜態壓縮器清單。

defmodule MyApp.BrotliCompressor do
  @behaviour Phoenix.Digester.Compressor

  def compress_file(file_path, content) do
    valid_extension = Path.extname(file_path) in Application.fetch_env!(:phoenix, :gzippable_exts)
    {:ok, compressed_content} = :brotli.encode(content)

    if valid_extension && byte_size(compressed_content) < byte_size(content) do
      {:ok, compressed_content}
    else
      :error
    end
  end

  def file_extensions do
    [".br"]
  end
end

# config/config.exs
config :phoenix,
  static_compressors: [Phoenix.Digester.Gzip, MyApp.BrotliCompressor],
  # ...

摘要

回呼

連結至這個回呼

compress_file(t, binary)

檢視原始碼
@callback compress_file(Path.t(), binary()) :: {:ok, binary()} | :error
@callback file_extensions() :: [String.t(), ...]