forked from reactjs/react-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.rb
42 lines (33 loc) · 1.39 KB
/
server.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# This file provided by Facebook is for non-commercial testing and evaluation
# purposes only. Facebook reserves all rights not expressly granted.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'webrick'
require 'json'
port = ENV['PORT'].nil? ? 3000 : ENV['PORT'].to_i
puts "Server started: http://localhost:#{port}/"
root = File.expand_path './public'
server = WEBrick::HTTPServer.new :Port => port, :DocumentRoot => root
server.mount_proc '/comments.json' do |req, res|
comments = JSON.parse(File.read('./comments.json'))
if req.request_method == 'POST'
# Assume it's well formed
comment = {}
req.query.each do |key, value|
comment[key] = value.force_encoding('UTF-8')
end
comments << comment
File.write('./comments.json', JSON.pretty_generate(comments, :indent => ' '))
end
# always return json
res['Content-Type'] = 'application/json'
res['Cache-Control'] = 'no-cache'
res.body = JSON.generate(comments)
end
trap 'INT' do server.shutdown end
server.start