1 | require 'webrick'
|
2 | require 'net/http'
|
3 | require 'base64'
|
4 | require 'json'
|
5 |
|
6 | require 'httparty'
|
7 |
|
8 | require_relative '__NOW_HANDLER_FILENAME'
|
9 |
|
10 | SupportedHTTPMethods = {
|
11 | 'GET' => Net::HTTP::Get,
|
12 | 'POST' => Net::HTTP::Post,
|
13 | 'PATCH' => Net::HTTP::Patch,
|
14 | 'PUT' => Net::HTTP::Put,
|
15 | 'DELETE' => Net::HTTP::Delete,
|
16 | 'HEAD' => Net::HTTP::Head,
|
17 | 'OPTIONS' => Net::HTTP::Options,
|
18 | 'MOVE' => Net::HTTP::Move,
|
19 | 'COPY' => Net::HTTP::Copy,
|
20 | 'MKCOL' => Net::HTTP::Mkcol,
|
21 | 'LOCK' => Net::HTTP::Lock,
|
22 | 'UNLOCK' => Net::HTTP::Unlock,
|
23 | }
|
24 |
|
25 | def now__handler(event:, context:)
|
26 | if not Object.const_defined?('Handler')
|
27 | return { :statusCode => 500, :body => 'Handler not defined in lambda' }
|
28 | end
|
29 |
|
30 | payload = JSON.parse(event['body'])
|
31 | path = payload['path']
|
32 | headers = payload['headers']
|
33 | httpMethod = payload['method']
|
34 | encoding = payload['encoding']
|
35 | body = payload['body']
|
36 |
|
37 | if not SupportedHTTPMethods.key?(httpMethod)
|
38 | return { :statusCode => 405, :body => 'Method Not Allowed' }
|
39 | end
|
40 |
|
41 | if (not body.nil? and not body.empty?) and (not encoding.nil? and encoding == 'base64')
|
42 | body = Base64.decode64(body)
|
43 | end
|
44 |
|
45 | server = WEBrick::HTTPServer.new :Port => 3000
|
46 |
|
47 | if Handler.is_a?(Proc)
|
48 | server.mount_proc '/', Handler
|
49 | else
|
50 | server.mount '/', Handler
|
51 | end
|
52 |
|
53 | Thread.new(server) do |server|
|
54 | server.start
|
55 | end
|
56 |
|
57 | req = HTTParty::Request.new(
|
58 | SupportedHTTPMethods[httpMethod],
|
59 | 'http://localhost:3000' + path,
|
60 | {
|
61 | headers: headers,
|
62 | body: body,
|
63 | }
|
64 | )
|
65 |
|
66 | res = req.perform
|
67 |
|
68 | return_hashmap = {
|
69 | :statusCode => res.code,
|
70 | :headers => res.headers
|
71 | }
|
72 |
|
73 | if not res.nil?
|
74 | return_hashmap['body'] = res.body
|
75 | end
|
76 |
|
77 | return_hashmap
|
78 | end
|