2016-07-14 106 views
0

我開發了一個簡單的web應用程序與sinatra和紅寶石,我有兩個文件:app.rb是我的sinatra應用程序和test.cgi是一個CGI程序。我需要執行CGI腳本,例如:CGI在紅寶石sinatra服務器

#!/usr/bin/env ruby 
# encoding: utf-8 
# app.rb 

require "sinatra" 

get "/form" do 
    File.read("my_web_form.html") 
end 

post "/form" do 
    # I need execute the CGI script, but this not works: 
    cgi "text.cgi" 
end 

我的CGI腳本是自定義語言(我有我創建一個解釋器),我嘗試把它嵌入到Web應用程序。謝謝。

+0

*以哪種方式*不起作用?如果您不告訴我們問題是什麼,我們無法幫助解決您的問題。請編輯您的問題,儘可能詳細地包含您的問題。 –

+0

你不需要Sinatra的CGI程序。將代碼編寫爲'get'或'post'處理程序。 Sinatra主頁很好地解釋了它。 CGI是*非常*老派。 –

+0

CGI令人難以置信的過時。任何你使用它的理由? –

回答

1

我已經做了一些搜索,我無法找到一種方式來「嘗試CGI」(這是直觀的方式)。

但是,您似乎可以運行Sinata CGI。有關代碼示例,請參見here

我實際上是在前幾天嘗試這樣做,我想我放棄了。但看到你的問題鼓勵我去弄明白。查看如何從西納特拉渲染CGI下面的例子:

樣本CGI文件,說這是在./app.cgichmod +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!