Uh oh!
There was an error while loading. Please reload this page.
This repository was archived by the owner on Jul 19, 2019. It is now read-only.
- Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathserver.rb
More file actions
Latest commit
49 lines (40 loc) · 1.62 KB
/
Copy pathserver.rb
File metadata and controls
49 lines (40 loc) · 1.62 KB
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
43
44
45
46
47
48
49
# 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'
# default port to 3000 or overwrite with PORT variable by running
# $ PORT=3001 ruby server.rb
port=ENV['PORT'] ? ENV['PORT'].to_i : 3000
puts"Server started: http://localhost:#{port}/"
root=File.expand_path'./public'
server=WEBrick::HTTPServer.newPort: port,DocumentRoot: root
server.mount_proc'/api/comments'do |req,res|
comments=JSON.parse(File.read('./comments.json',encoding: 'UTF-8'))
ifreq.request_method == 'POST'
# Assume it's well formed
comment={id: (Time.now.to_f * 1000).to_i}
req.query.eachdo |key,value|
comment[key]=value.force_encoding('UTF-8')unlesskey == 'id'
end
comments << comment
File.write(
'./comments.json',
JSON.pretty_generate(comments,indent: ' '),
encoding: 'UTF-8'
)
end
# always return json
res['Content-Type']='application/json'
res['Cache-Control']='no-cache'
res['Access-Control-Allow-Origin']='*'
res.body=JSON.generate(comments)
end
trap('INT'){server.shutdown}
server.start