read-from-html

Learn how to read and serve HTML content dynamically using Ruby

Ruby WEBrick HTML Reader

Understanding Ruby WEBrick for HTML Serving

This example demonstrates how to use Ruby's built-in WEBrick library to create a simple HTTP server that can read and serve HTML files. WEBrick is a lightweight HTTP server that is useful for development and small-scale applications. It allows you to serve static files or dynamically generate content based on incoming requests.

Reading and Serving Dynamic HTML Content

The provided Ruby script initializes a WEBrick HTTP server. It's configured to listen on port 80 and set the document root to /var/www/app. The core functionality lies within the mount_proc block, which handles incoming requests. When a request is made to the root path ('/'), the server reads the content of /var/www/app/index.html. It then uses the sub method to replace a placeholder string "HEADER_TEXT" with "Hello", making the content dynamic before sending it back as the HTTP response. This technique is fundamental for serving personalized or updated content without manually editing HTML files for every change.

Ruby WEBrick Server Implementation

require 'webrick'

server = WEBrick::HTTPServer.new(
    :Port => 80,
    :SSLEnable => false,
    :DocumentRoot => '/var/www/app'
)

server.mount_proc('/') do |request, response|
    response.content_type = 'text/html; charset=utf-8'
    response.body = File.read('/var/www/app/index.html').sub("HEADER_TEXT", "Hello")
end

trap 'INT' do server.shutdown end

server.start

Key Components of the Ruby Script

  • require 'webrick': Imports the necessary WEBrick library.
  • WEBrick::HTTPServer.new(...): Initializes the HTTP server with configuration options like port, SSL status, and document root.
  • server.mount_proc('/') do ... end: Defines a handler for requests to the root URL.
  • response.content_type = 'text/html; charset=utf-8': Sets the correct MIME type for the response.
  • File.read('/var/www/app/index.html'): Reads the content of the specified HTML file.
  • .sub("HEADER_TEXT", "Hello"): Replaces the placeholder text within the HTML content.
  • trap 'INT' do server.shutdown end: Allows graceful shutdown of the server using Ctrl+C.
  • server.start: Starts the WEBrick server, making it listen for incoming connections.

Further Learning and Resources

For more advanced web development with Ruby, consider exploring frameworks like Ruby on Rails or Sinatra. These frameworks provide more robust solutions for routing, templating, database integration, and other common web application tasks. Understanding the fundamentals of HTTP servers like WEBrick is a valuable starting point for any Ruby web developer.