Ruby: простой Web Server на базе WEBrick

В Ruby есть встроенный сервер WEBrick. У него есть довольно богатый функционал, но юзать его не рекомендуют (как минимум из-за отсутствия документации и однопоточности). Для целей production могут использоваться другие ruby-сервера: puma, unicorn, rainbows.

WEBrick::HTTPAuth
WEBrick::HTTPAuth::Authenticator
WEBrick::HTTPAuth::BasicAuth
WEBrick::HTTPAuth::DigestAuth
WEBrick::HTTPAuth::Htdigest
WEBrick::HTTPAuth::Htgroup
WEBrick::HTTPAuth::Htpasswd
WEBrick::HTTPAuth::ProxyAuthenticator
WEBrick::HTTPAuth::ProxyBasicAuth
WEBrick::HTTPAuth::ProxyDigestAuth
WEBrick::HTTPAuth::UserDB
WEBrick::Cookie

Поднимаем простой http сервер. Взято прямо из wiki и rubydoc.

#Include WEBrick class with require
require 'webrick'

#FileHandler servlet provides the option to choose which files from user to serve
#The following code shows how to serve them from the folder '~/'
root = File.expand_path '~/'

#Instantiating a new server with HTTPServer.new on port 1234 serving the documents from root folder
server = WEBrick::HTTPServer.new :Port => 1234, :DocumentRoot => root

#The following proc is used to customize the server operations
server.mount_proc '/' do |request, response|
 response.body = 'Hello, world!'
end

#The following command will provide a hook to shutdown the server (often done with Ctrl+C)
trap('INT') {server.shutdown}

#Start the server
server.start

Поднимаем https сервер с заданным сертификатом.

#!/usr/bin/env ruby
#coding: utf-8

# Created by Petr V. Redkin

#Include WEBrick class with require
require 'webrick'
require 'webrick/https'
require 'openssl'

#FileHandler servlet provides the option to choose which files from user to serve
#The following code shows how to serve them from the folder '~/'
root = File.expand_path '~/'

#Instantiating a new server with HTTPServer.new on port 1234 serving the documents from root folder
cert = OpenSSL::X509::Certificate.new File.read '/etc/letsencrypt/live/my_site.net/cert.pem'
pkey = OpenSSL::PKey::RSA.new File.read '/etc/letsencrypt/live/my_site.net/privkey.pem'
server = WEBrick::HTTPServer.new(:Port => 1234,
 :SSLEnable => true,
 :SSLCertificate => cert,
 :SSLPrivateKey => pkey)

#The following proc is used to customize the server operations
server.mount_proc '/' do |request, response|
 response.body = 'Hello, world!'
end

#The following command will provide a hook to shutdown the server (often done with Ctrl+C)
trap('INT') {server.shutdown}

#Start the server
server.start

Leave a Reply