我已经进行了一些搜索,但我无法找到一种以您尝试的方式“渲染 CGI”的方法(这是直观的方式)。
不过,您似乎可以从 CGI 运行Sinata。代码示例见here。
几天前我实际上试图这样做,我想我放弃了。但是看到你的问题鼓励我弄清楚。请参阅以下示例,了解如何从 sinatra 渲染 CGI:
一个示例 CGI 文件,假设它位于 ./app.cgi 和 chmod +x 已运行
#!/usr/bin/env ruby
require "cgi"
cgi = CGI.new("html4")
cgi.out{
cgi.html{
cgi.head{ "\n"+cgi.title{"This Is a Test"} } +
cgi.body{ "\n"+
cgi.h1 { "This is a Test" } + "\n"+
}
}
}
一个定义render_cgi方法的模块:
class RenderCgiError < StandardError
end
module RenderCgi
def render_cgi(filepath, options={})
headers_string, body = run_cgi_and_parse_output(filepath, options)
headers_hash = parse_headers_string(headers_string)
response = Rack::Response.new
headers_hash.each { |k,v| response.header[k] = v }
response.body << body
response
end
private
def run_cgi_and_parse_output(filepath, options={})
options_string = options.reduce("") { |str, (k,v)| str << "#{k}=#{v} " }
# make sure options has at least one key-val pair, otherwise running the CGI may hang
if options_string.split("=").select { |part| (part&.length || -1) > 0 }.length < 2
raise(RenderCgiError, "one truthy key and associated truthy val is required for options")
end
output = `sh #{filepath} #{options_string}`
headers_string, body = output.split("\n\r")
return [headers_string, body]
end
def parse_headers_string(string)
return string.split("\n").reduce({}) do |results, line|
key, val = line.split(": ")
results[key.chomp] = val.chomp
next results
end
end
end
以及运行它的 Sinatra 应用程序
require 'sinatra'
class MyApp < Sinatra::Base
include RenderCgi
get '/' do
render_cgi("./app.cgi", { "foo" => "bar" })
end
end
MyApp.run!