Class: Pindo::WebServer::BrotliFileHandler

Inherits:
WEBrick::HTTPServlet::AbstractServlet
  • Object
show all
Defined in:
lib/pindo/module/webserver/brotli_file_handler.rb

Overview

处理.br扩展名请求的servlet

Instance Method Summary collapse

Constructor Details

#initialize(server, root_dir, debug = false) ⇒ BrotliFileHandler

Returns a new instance of BrotliFileHandler.



14
15
16
17
18
# File 'lib/pindo/module/webserver/brotli_file_handler.rb', line 14

def initialize(server, root_dir, debug=false)
    super(server)
    @root_dir = root_dir
    @debug = debug
end

Instance Method Details

#do_GET(req, res) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/pindo/module/webserver/brotli_file_handler.rb', line 20

def do_GET(req, res)
    # 只处理.br结尾的文件
    unless req.path.end_with?('.br')
        res.status = 404
        return
    end
  
    file_path = File.join(@root_dir, req.path[1..-1])
  
    if File.exist?(file_path)
        # 确定原始文件类型
        base_name = File.basename(req.path, ".br")
        ext = File.extname(base_name)
        
        content_type = case ext
            when ".js" then "application/javascript"
            when ".wasm" then "application/wasm"
            when ".data" then "application/octet-stream"
            when ".json" then "application/json"
            else "application/octet-stream"
        end
        
        # 读取文件
        file_content = File.binread(file_path)
        
        # 设置响应
        res.status = 200
        res.header["Content-Encoding"] = "br"
        res.content_type = content_type
        res.body = file_content
    else
        res.status = 404
    end
end