WEBrick server
| Serve a directory | |
| Mount a proc | |
| Serve JSON | |
| Trap INT to stop |
Serve a directory
WEBrick ships with Ruby and serves static files with two lines of code. Point DocumentRoot at a folder and start the server.
Open the shown port in a browser to browse the folder content during local development.
require "webrick"
server = WEBrick::HTTPServer.new(Port: 8000, DocumentRoot: ".")
server.start
Mount a proc
Dynamic paths need code, not files. Mount a path with a block that receives the request and builds the response.
The block runs on every visit, so the response can depend on query params, headers, and time of day.
require "webrick"
server = WEBrick::HTTPServer.new(Port: 8000)
server.mount_proc("/hello") do |req, res|
res.body = "hi"
end
server.start
Serve JSON
Small APIs return JSON instead of HTML pages. Set the content type header and dump a Ruby structure with JSON generate.
Clients parse the body back into arrays and hashes, exactly as the JSON lesson describes.
require "webrick"
require "json"
server = WEBrick::HTTPServer.new(Port: 8000)
server.mount_proc("/todos") do |req, res|
res["Content-Type"] = "application/json"
res.body = JSON.generate([{ title: "write tests" }])
end
server.start
Trap INT to stop
A server started from the terminal owns that terminal until it stops. Trap the interrupt signal so Control plus C shuts it down cleanly.
Without the trap the process may need a forced kill, which can leave the port busy for a while.
require "webrick"
server = WEBrick::HTTPServer.new(Port: 8000)
trap("INT") { server.shutdown }
server.start
curl http://localhost:8000/hello
hi
Next: Rails in one lesson
Article author: Arthur Isaev