Ruby webrick: Difference between revisions
From wikinotes
No edit summary |
(→Server) |
||
Line 18: | Line 18: | ||
<blockquote> | <blockquote> | ||
<syntaxhighlight lang="ruby"> | <syntaxhighlight lang="ruby"> | ||
require "webrick" | |||
class App | class App | ||
def self.run! | def self.run! |
Latest revision as of 01:59, 13 May 2022
webrick is an HTTP server library builtin to ruby.
Documentation
official docs https://docs.ruby-lang.org/en/2.7.0/WEBrick.html
Usage
Routes are defined in classes, and get mounted to the app.
There are several configuration options, you can even serve files like a regular webserver.Server
require "webrick" class App def self.run! server = WEBrick::HTTPServer.new(port: 8000) # mount classes as routes server.mount("/", Index) server.mount("/thing", Thing) trap("INT") { server.shutdown } server.start end endGET/POST
require "webrick" class Index < WEBrick::HTTPServlet::AbstractServlet def do_GET(request, response) response.status = 200 response["Content-Type"] = "text/html" response.body = <<~HTML <html> ... </html> <body><p>hello</p></body> </html> HTML end end