Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Server to echo HTTP requests.
# usage: ruby echo_server.rb
#
# Launches a WEBRick server that echos http requests back. This can be
# useful when debugging HTTP requests.
#
require 'webrick'
# Setup server configuration
logger = WEBrick::Log.new
config = {
:Port => 2000,
:Logger => logger,
:AccessLog => [
[ logger, WEBrick::AccessLog::COMMON_LOG_FORMAT ],
[ logger, WEBrick::AccessLog::REFERER_LOG_FORMAT ]]
}
# setup server
server = WEBrick::HTTPServer.new(config)
server.mount_proc("/") do |req, res|
res.body << req.request_line
res.body << req.raw_header.join('')
# an extra line must be added to delimit the headers from the body.
if req.body
res.body << "\r\n"
res.body << req.body
end
res['Content-Type'] = "text/plain"
end
# set signals and run
['INT', 'TERM'].each do |signal|
trap(signal) { server.shutdown }
end
server.start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.