hello_world.rb 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. # frozen_string_literal: true
  2. # Configure Slim templating engine
  3. Slim::Engine.set_options :format=>:html, :sort_attrs=>false
  4. # Our Rack application to be executed by rackup
  5. class HelloWorld < Sinatra::Base
  6. configure do
  7. # Static file serving is ostensibly disabled in modular mode but Sinatra
  8. # still calls an expensive Proc on every request...
  9. disable :static
  10. # XSS, CSRF, IP spoofing, etc. protection are not explicitly required
  11. disable :protection
  12. # Only add the charset parameter to specific content types per the requirements
  13. set :add_charset, [mime_type(:html)]
  14. end
  15. helpers do
  16. def bounded_queries
  17. queries = params[:queries].to_i
  18. return QUERIES_MIN if queries < QUERIES_MIN
  19. return QUERIES_MAX if queries > QUERIES_MAX
  20. queries
  21. end
  22. def json(data)
  23. content_type :json
  24. JSON.fast_generate(data)
  25. end
  26. # Return a random number between 1 and MAX_PK
  27. def rand1
  28. rand(MAX_PK).succ
  29. end
  30. end
  31. after do
  32. response['Date'] = Time.now.httpdate
  33. end
  34. after do
  35. response['Server'] = SERVER_STRING
  36. end if SERVER_STRING
  37. # Test type 1: JSON serialization
  38. get '/json' do
  39. json :message=>'Hello, World!'
  40. end
  41. # Test type 2: Single database query
  42. get '/db' do
  43. json World.with_pk(rand1).values
  44. end
  45. # Test type 3: Multiple database queries
  46. get '/queries' do
  47. worlds =
  48. DB.synchronize do
  49. Array.new(bounded_queries) do
  50. World.with_pk(rand1)
  51. end
  52. end
  53. json worlds.map!(&:values)
  54. end
  55. # Test type 4: Fortunes
  56. get '/fortunes' do
  57. @fortunes = Fortune.all
  58. @fortunes << Fortune.new(
  59. :id=>0,
  60. :message=>'Additional fortune added at request time.'
  61. )
  62. @fortunes.sort_by!(&:message)
  63. slim :fortunes
  64. end
  65. # Test type 5: Database updates
  66. get '/updates' do
  67. worlds =
  68. DB.synchronize do
  69. Array.new(bounded_queries) do
  70. world = World.with_pk(rand1)
  71. world.update(:randomnumber=>rand1)
  72. world
  73. end
  74. end
  75. json worlds.map!(&:values)
  76. end
  77. # Test type 6: Plaintext
  78. get '/plaintext' do
  79. content_type :text
  80. 'Hello, World!'
  81. end
  82. end