跳到內容 跳到搜尋

Action Dispatch FileHandler

這個端點使用 Rack::Files 從磁碟提供靜態檔案。

根據預期的慣例將 URL 路徑與靜態檔案配對:pathpath.html、path/index.html。

首先會檢查這些檔案的預壓縮版本。支援 Brotli (.br) 和 gzip (.gz) 檔案。如果存在 path.br,這個端點會傳回該檔案,且帶有 content-encoding: br 標頭。

如果找不到相符的檔案,這個端點會回應 404 Not Found

傳遞 root 目錄以搜尋相符的檔案,選擇性的 index: "index" 來變更預設的 path/index.html,以及選擇性的其他回應標頭。

方法
A
C
N

常數

PRECOMPRESSED = { "br" => ".br", "gzip" => ".gz", "identity" => nil }
 

Accept-Encoding 值 -> 檔案副檔名

類別公用方法

new(root, index: "index", headers: {}, precompressed: %i[ br gzip ], compressible_content_types: /\A(?:text\/|application\/javascript|image\/svg\+xml)/)

# File actionpack/lib/action_dispatch/middleware/static.rb, line 55
def initialize(root, index: "index", headers: {}, precompressed: %i[ br gzip ], compressible_content_types: /\A(?:text\/|application\/javascript|image\/svg\+xml)/)
  @root = root.chomp("/").b
  @index = index

  @precompressed = Array(precompressed).map(&:to_s) | %w[ identity ]
  @compressible_content_types = compressible_content_types

  @file_server = ::Rack::Files.new(@root, headers)
end

實例公用方法

attempt(env)

# File actionpack/lib/action_dispatch/middleware/static.rb, line 69
def attempt(env)
  request = Rack::Request.new env

  if request.get? || request.head?
    if found = find_file(request.path_info, accept_encoding: request.accept_encoding)
      serve request, *found
    end
  end
end

call(env)

# File actionpack/lib/action_dispatch/middleware/static.rb, line 65
def call(env)
  attempt(env) || @file_server.call(env)
end