Ruby で超簡単な CGI

エラーが出て全然わからない。

$ ruby test_webrick.rb
[2020-04-01 22:31:56] INFO  WEBrick 1.6.0
[2020-04-01 22:31:56] INFO  ruby 2.7.0 (2019-12-25) [x86_64-linux]
[2020-04-01 22:31:56] INFO  WEBrick::HTTPServer#start: pid=15497 port=19681
[2020-04-01 22:32:00] ERROR CGIHandler: test_cgi.rb:\n/home/tomoki/.rbenv/versions/2.7.0/lib/ruby/2.7.0/webrick/httpservlet/cgi_runner.rb:47:in `exec': Not a directory - test_cgi.rb (Errno::ENOTDIR)\n\tfrom /home/tomoki/.rbenv/versions/2.7.0/lib/ruby/2.7.0/webrick/httpservlet/cgi_runner.rb:47:in `<main>'\n
[2020-04-01 22:32:00] ERROR CGIHandler: test_cgi.rb exit with 1
[2020-04-01 22:32:00] ERROR Premature end of script headers: test_cgi.rb
192.168.11.4 - - [01/Apr/2020:22:31:59 JST] "GET /cgi HTTP/1.1" 500 328
- -> /cgi

 

解決

ここでようやく解決。CGIInterpreter: WEBrick::HTTPServlet::CGIHandler::Ruby の指定が必要だった。
 
サーバ側。これは先に実行する。
test_webrick_localhost.rb

require "webrick"

server = WEBrick::HTTPServer.new({
  DocumentRoot: './',
  BindAddress: "127.0.0.1",
  CGIInterpreter: WEBrick::HTTPServlet::CGIHandler::Ruby,
  Port: 19681
})

server.mount('/test_cgi', WEBrick::HTTPServlet::CGIHandler, 'test_cgi.rb')
server.mount('/test', WEBrick::HTTPServlet::FileHandler, 'test.html')
Signal.trap(:INT) {server.shutdown}
server.start

 
で、CGI用のコード。
test_cgi.rb

#!/usr/bin/env/ruby
require "cgi"

cgi = CGI.new "html4"

cgi.out do
  cgi.html do
    cgi.head { cgi.title {"CGI TEST"} } +
    cgi.body do
      cgi.p {"CGI TEST"}
    end
  end
end

実行権限を与えておく。で、ブラウザで http://localhost:19681/test_cgi にアクセスする。

また、test.html を書いておいて http://localhost:19681/test にアクセスすると、HTML がブラウザで実行される。

Ruby 2.7.0、Linux Mint 19.3、ブラウザは Chrome 80.0 で確認。
 

他の例

nyanko.rb

#!/usr/bin/env/ruby
require "cgi"

cgi = CGI.new "html4"

cgi.out do
  cgi.html do
    cgi.head { cgi.meta({charset: "UTF-8"}) + cgi.title {"CGI TEST"} } +
    cgi.body do
      cgi.p {"にゃんこ"} +
      cgi.img({src: "neko.jpg"})
    end
  end
end

http://localhost:19681/nyanko