思考実験室

日々のつれづれ

RubyでサクッとCGI

Websocketを使って簡単なチャットを作ってみたい。とりあえず、どこかのサーバにリクエストを送ったらws / wss プロトコルで返ってくればいいはず。 Webscoketでも使用するポートは同じなので、まずは素のHTMLを返す処理を作ってあげます。 以下の Vagrantfile を用意します。

# -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant.configure("2") do |config|
  config.vm.box = "bento/centos-7.6"
  config.vm.network "private_network", ip: "192.168.33.10"

  # Apacheにて権限を変更しておかないと実行ができない
  config.vm.synced_folder "./cgi","/home/cgi-resources", mount_options: ['dmode=755','fmode=755']
end

ホストOS側では以下を実行します。

# cgi用のリソースを置くために用意しておく
$ mkdir cgi

# Vagrantを実行
$ vagrant up --provision

起動が完了したら、 vagrant ssh コマンドで、リモートホストにアクセスし、apacherubyをインストールする。
そもそも論では、インラインシェルで書くべきで、rubyも2.0しかインストールされませんが、確認用なのであまり気にせずやっていきましょう。

$ yum -y install httpd
$ systemctl enable httpd.service
$ sudo yum -y intall ruby

/etc/httpd/conf/httpd.conf を確認すると

# Supplemental configuration
#
# Load config files in the "/etc/httpd/conf.d" directory, if any.
IncludeOptional conf.d/*.conf

とあるように、apache/etc/httpd/conf.d 配下に、拡張子 .conf を設定したファイルを配置すれば、 httpd.conf を直接いじる必要はないです。

cgi-setting.conf

Alias /cgi home/cgi-resources
<Directory "home/cgi-resources">
  Require all granted
  Options +ExecCGI
  AddHandler cgi-script .rb
</Directory>

もちろん、 sudo systemctl restart httpd を忘れずに。 そして最後にrubyファイルを設置します。

home/cgi-resources/hello.rb

#!/bin/ruby

print "Content-type: text/html\n\n"
print "<html>"
print "<body><h1>Hello, cgi</h1><h2>this is ruby</h2></body>"
print "</html>"

http://192.168.33.10/cgi/hello.rb にアクセスすると、先ほどの記載した内容が表示されるはずです。

覚えたこと

  • /etc/httpd/conf.d/*.conf を追加すると、 httpd.conf を直接編集せずとも設定の追加ができる
  • RubyCGI処理は意外とハマる、こういうときのphpはめっちゃ楽