Class: Fluent::PluginHelper::HttpServer::Compat::WebrickHandler

Inherits:
Object
  • Object
show all
Defined in:
lib/fluent/plugin_helper/http_server/compat/webrick_handler.rb

Class Method Summary collapse

Class Method Details

.build(get: nil, head: nil, post: nil, put: nil, patch: nil, delete: nil, connect: nil, options: nil, trace: nil) ⇒ Object

**opt is enough. but I wrote a signature explicitly for readability



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/fluent/plugin_helper/http_server/compat/webrick_handler.rb', line 26

def self.build(get: nil, head: nil, post: nil, put: nil, patch: nil, delete: nil, connect: nil, options: nil, trace: nil)
  opt = { get: get, head: head, post: post, put: put, patch: patch, delete: delete, connect: connect, options: options, trace: trace }

  Class.new(WEBrick::HTTPServlet::AbstractServlet) do
    HttpServer::Methods::ALL.each do |name|
      define_method("do_#{name}") do |request, response|
        code, headers, body =
                       if request.path_info != ''
                         render_json(404, 'message' => 'Not found')
                       else
                         begin
                           opt[name.downcase.to_sym].call(request)
                         rescue => _
                           render_json(500, 'message' => 'Something went wrong')
                         end
                       end

        response.status = code
        headers.each { |k, v| response[k] = v }
        response.body = body
      end
    end

    def render_json(code, obj)
      [code, { 'Content-Type' => 'application/json' }, obj.to_json]
    end
  end
end