Ruby webrick: Difference between revisions

From wikinotes
(Created page with "webrick is an HTTP server library builtin to ruby. = Documentation = <blockquote> {| class="wikitable" |- | official docs || https://docs.ruby-lang.org/en/2.7.0/WEBrick.html...")
 
 
(One intermediate revision by the same user not shown)
Line 9: Line 9:
|}
|}
</blockquote><!-- Documentation -->
</blockquote><!-- Documentation -->
= Usage =
<blockquote>
Routes are defined in classes, and get mounted to the app.<br>
There are several configuration options, you can even serve files like a regular webserver.
== Server ==
<blockquote>
<syntaxhighlight lang="ruby">
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
end
</syntaxhighlight>
</blockquote><!-- Server -->
== GET/POST ==
<blockquote>
<syntaxhighlight lang="ruby">
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
</syntaxhighlight>
</blockquote><!-- GET/POST -->
</blockquote><!-- Usage -->

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
end

GET/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