Create a gist now

Instantly share code, notes, and snippets.

@suruseas /server.rb
Last active Sep 15, 2017

What would you like to do?
Sinatra(WEBrick)でsslサーバをたてる
# -*- coding: utf-8 -*-
require 'sinatra/base'
require 'pp'
require 'webrick'
require 'webrick/https'
require 'openssl'
CRT_FILE_NAME = 'server.crt'
RSA_FILE_NAME = 'server.key'
#初期起動時に鍵を自動生成する
unless File.exists?(CRT_FILE_NAME) || File.exists?(RSA_FILE_NAME)
crt, rsa = WEBrick::Utils::create_self_signed_cert(1024, [["CN", WEBrick::Utils::getservername]], 'Generated by Ruby/OpenSSL')
File.open(CRT_FILE_NAME, "w") {|f| f.write crt}
File.open(RSA_FILE_NAME, "w") {|f| f.write rsa}
end
webrick_options = {
:Port => 443,
:Logger => WEBrick::Log::new($stderr, WEBrick::Log::DEBUG),
:SSLEnable => true,
:SSLVerifyClient => OpenSSL::SSL::VERIFY_NONE,
:SSLCertificate => OpenSSL::X509::Certificate.new(File.open(CRT_FILE_NAME).read),
:SSLPrivateKey => OpenSSL::PKey::RSA.new(File.open(RSA_FILE_NAME).read)
}
class Apps < Sinatra::Base
set :logging, false
get '/favicon.ico' do
'Nothing'
end
end
#WEBrickを自力で起動させる場合、Ctrl+Cで止めるには以下のトラップコードが必要
Rack::Handler::WEBrick.run Apps, webrick_options do |server|
shutdown_proc = ->( sig ){ server.shutdown() }
[ :INT, :TERM ].each{ |e| Signal.trap( e, &shutdown_proc ) }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment