Class: Kanal::Interfaces::Pachka::Helpers::LocalServer
- Inherits:
-
Object
- Object
- Kanal::Interfaces::Pachka::Helpers::LocalServer
- Defined in:
- lib/kanal/interfaces/pachka/helpers/local_server.rb
Overview
This class starts web server and accepts requests on api endpoint
Instance Method Summary collapse
-
#initialize(host, port) ⇒ LocalServer
constructor
A new instance of LocalServer.
-
#on_request(&block) ⇒ void
Provide block to this method which will be called with has parameters from json body.
-
#start_accepting_requests ⇒ void
Method to start web server and accept requests.
Constructor Details
#initialize(host, port) ⇒ LocalServer
Returns a new instance of LocalServer.
18 19 20 21 22 |
# File 'lib/kanal/interfaces/pachka/helpers/local_server.rb', line 18 def initialize(host, port) @on_request_block = nil @host = host @port = port end |
Instance Method Details
#on_request(&block) ⇒ void
This method returns an undefined value.
Provide block to this method which will be called with has parameters from json body
31 32 33 |
# File 'lib/kanal/interfaces/pachka/helpers/local_server.rb', line 31 def on_request(&block) @on_request_block = block end |
#start_accepting_requests ⇒ void
This method returns an undefined value.
Method to start web server and accept requests. Requests are accepted on @host:@port where @port is provided in constructor Endpoint: /api/bod Accepts only method POST and application/json Content-Type After request accepted it“s body is parsed and passed to @on_request_block
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
# File 'lib/kanal/interfaces/pachka/helpers/local_server.rb', line 44 def start_accepting_requests server = WEBrick::HTTPServer.new(Host: @host, Port: @port) server.mount_proc "/api/bot" do |req, res| if req.request_method == "POST" && req.content_type == "application/json" begin body = JSON.parse(req.body) @on_request_block&.call(body) rescue JSON::ParserError res.status = 400 res.body = "Bad Request" end else res.status = 405 res.body = "Method Not Allowed" end res["Content-Type"] = "text/plain" res["Content-Length"] = res.body.length end trap("INT") { server.shutdown } server.start end |