跳到內容 跳到搜尋

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)/)

# File actionpack/lib/action_dispatch/middleware/static.rb, line 53
def initialize(root, index: "index", headers: {}, precompressed: %i[ br gzip ], compressible_content_types: /\A(?:text\/|application\/javascript)/)
  @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 67
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 63
def call(env)
  attempt(env) || @file_server.call(env)
end