server.rb 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #!/usr/bin/env ruby
  2. # encoding: utf-8
  3. require 'webrick'
  4. include WEBrick
  5. $:.unshift 'ext'
  6. $:.unshift 'lib'
  7. require 'json'
  8. class JSONServlet < HTTPServlet::AbstractServlet
  9. @@count = 1
  10. def do_GET(req, res)
  11. obj = {
  12. "TIME" => Time.now.strftime("%FT%T"),
  13. "foo" => "Bär",
  14. "bar" => "© ≠ €!",
  15. 'a' => 2,
  16. 'b' => 3.141,
  17. 'COUNT' => @@count += 1,
  18. 'c' => 'c',
  19. 'd' => [ 1, "b", 3.14 ],
  20. 'e' => { 'foo' => 'bar' },
  21. 'g' => "松本行弘",
  22. 'h' => 1000.0,
  23. 'i' => 0.001,
  24. 'j' => "\xf0\xa0\x80\x81",
  25. }
  26. res.body = JSON.generate obj
  27. res['Content-Type'] = "application/json"
  28. end
  29. end
  30. def create_server(err, dir, port)
  31. dir = File.expand_path(dir)
  32. err.puts "Surf to:", "http://#{Socket.gethostname}:#{port}"
  33. s = HTTPServer.new(
  34. :Port => port,
  35. :DocumentRoot => dir,
  36. :Logger => WEBrick::Log.new(err),
  37. :AccessLog => [
  38. [ err, WEBrick::AccessLog::COMMON_LOG_FORMAT ],
  39. [ err, WEBrick::AccessLog::REFERER_LOG_FORMAT ],
  40. [ err, WEBrick::AccessLog::AGENT_LOG_FORMAT ]
  41. ]
  42. )
  43. s.mount("/json", JSONServlet)
  44. s
  45. end
  46. default_dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'data'))
  47. dir = ARGV.shift || default_dir
  48. port = (ARGV.shift || 6666).to_i
  49. s = create_server(STDERR, dir, 6666)
  50. t = Thread.new { s.start }
  51. trap(:INT) do
  52. s.shutdown
  53. t.join
  54. exit
  55. end
  56. sleep