Class: Pindo::WebServer::WebGlServerHelper

Inherits:
Object
  • Object
show all
Defined in:
lib/pindo/module/webserver/webgl_server_helper.rb

Overview

WebGL服务器辅助类用于配置和启动WebGL预览服务器

Class Method Summary collapse

Class Method Details

.get_local_ipObject

获取本机局域网IP地址



178
179
180
181
182
183
184
185
186
187
# File 'lib/pindo/module/webserver/webgl_server_helper.rb', line 178

def self.get_local_ip
  ip = nil
  Socket.ip_address_list.each do |addr_info|
    if addr_info.ipv4? && !addr_info.ipv4_loopback?
      ip = addr_info.ip_address
      break
    end
  end
  return ip || 'localhost'
end

.start_http_server(webgl_dir, port, debug = false) ⇒ Object

启动HTTP服务器



14
15
16
17
18
19
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/pindo/module/webserver/webgl_server_helper.rb', line 14

def self.start_http_server(webgl_dir, port, debug = false)
  begin
    # 确保目录存在
    unless File.directory?(webgl_dir)
      puts("错误: WebGL目录不存在: #{webgl_dir}")
      return nil
    end

    # 检查index.html是否存在
    if !File.exist?(File.join(webgl_dir, "index.html"))
      puts("警告: WebGL目录中未找到index.html文件")
    end

    # 创建自定义日志格式器,只记录错误
    custom_log = [
      [:error, WEBrick::AccessLog::COMMON_LOG_FORMAT],
    ]

    # 采用直接的方法配置服务器
    server = WEBrick::HTTPServer.new(
      :Port => port,
      :DocumentRoot => webgl_dir,
      :Logger => WEBrick::Log.new(nil, WEBrick::Log::ERROR),
      :AccessLog => debug ? nil : [],
      :DoNotReverseLookup => true,
      :BindAddress => '0.0.0.0'  # 绑定到所有网络接口,使其在局域网可访问
    )

    # 设置根路径处理器
    server.mount_proc("/") { |req, res|
      # 根路径请求直接提供WebGL内容
      if req.path == "/" || req.path == "/index.html"
        # 直接提供index.html,不再重定向到响应式预览
        index_path = File.join(webgl_dir, "index.html")
        if File.exist?(index_path)
          # 读取原始HTML内容
          original_html = File.read(index_path)
                          
          # 添加base标签以修复相对路径问题
          if !original_html.include?('<base href=')
            # 在<head>标签后插入base标签
            modified_html = original_html.gsub(/<head>/, '<head><base href="./">')
            res.body = modified_html
          else 
            res.body = original_html
          end
                          
          res.content_type = "text/html"
          res.status = 200
        else
          res.status = 404
          res.body = "WebGL index.html not found"
        end
      else
        # 对于非根路径,使用普通的静态文件处理
        path = req.path
        file_path = File.join(webgl_dir, path[1..-1])
                          
        if File.exist?(file_path) && !File.directory?(file_path)
          # 确定内容类型
          ext = File.extname(file_path)
          content_type = case ext
            when ".html" then "text/html"
            when ".js" then "application/javascript"
            when ".css" then "text/css"
            when ".png" then "image/png"
            when ".jpg", ".jpeg" then "image/jpeg"
            when ".gif" then "image/gif"
            when ".ico" then "image/x-icon"
            when ".wasm" then "application/wasm"
            when ".data" then "application/octet-stream"
            when ".json" then "application/json"
            else "application/octet-stream"
          end
                              
          # 设置Brotli压缩相关的响应头
          if file_path.end_with?('.br')
            res.header["Content-Encoding"] = "br"
            file_content = File.binread(file_path)
          else
            file_content = File.read(file_path)
          end
                              
          res.content_type = content_type
          res.body = file_content
          res.status = 200
        else
          res.status = 404
          res.body = "File not found: #{path}"
        end
      end
    }
    
    # 挂载一个特殊的处理器专门处理rawindex.html(供预览页面使用)
    server.mount_proc("/rawindex.html") { |req, res|
      index_path = File.join(webgl_dir, "index.html")
      if File.exist?(index_path)
        # 读取原始HTML内容
        original_html = File.read(index_path)
                          
        # 添加base标签以修复相对路径问题
        if !original_html.include?('<base href=')
          # 在<head>标签后插入base标签
          modified_html = original_html.gsub(/<head>/, '<head><base href="./">')
          res.body = modified_html
        else 
          res.body = original_html
        end
                          
        res.content_type = "text/html"
        res.status = 200
      else
        res.status = 404
        res.body = "WebGL index.html not found"
      end
    }
                  
    # 挂载响应式预览页面处理器
    server.mount("/responsive", Pindo::WebServer::ResponsivePreviewHandler, webgl_dir, port, debug)
                  
    # 挂载Brotli处理器(后缀为.br的文件)
    paths_with_br = []
    Find.find(webgl_dir) do |path|
      if path.end_with?('.br') && File.file?(path)
        rel_path = path.sub(webgl_dir, '')
        paths_with_br << rel_path
      end
    end
                  
    # 挂载每个.br文件
    paths_with_br.each do |br_path|
      server.mount(br_path, Pindo::WebServer::BrotliFileHandler, webgl_dir, debug)
    end
                  
    # 只在调试模式下显示详细信息
    if debug
      puts("找到.br文件: #{paths_with_br.join(', ')}")
                      
      puts("WebGL目录内容:")
      Dir.entries(webgl_dir).each do |entry|
        next if entry == "." || entry == ".."
        puts("  - #{entry}")
                          
        # 递归显示子目录中的文件(限制为一级)
        entry_path = File.join(webgl_dir, entry)
        if File.directory?(entry_path)
          Dir.entries(entry_path).each do |subentry|
            next if subentry == "." || subentry == ".."
            puts("    - #{entry}/#{subentry}")
          end
        end
      end
    end
                  
    # 返回配置好的服务器
    return server
  rescue Exception => e
    puts("启动HTTP服务器失败: #{e.message}")
    puts(e.backtrace.join("\n")) if debug
    return nil
  end
end