forked from mrtazz/http-test-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.rb
122 lines (100 loc) · 2.59 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
# frozen_string_literal: true
require 'rubygems'
require 'sinatra'
def disabled?(obj)
return false if obj.nil?
return true if %w[false no 0].include?(obj.to_s)
false
end
configure do
set :start_time, Time.now
end
disable :logging if disabled?(ENV['LOGGING'])
# simply accept calls
get '/?' do
'GET'
end
post '/?' do
'POST'
end
put '/?' do
'PUT'
end
delete '/?' do
'DELETE'
end
# return version environment variable for testing
get '/version?' do
env_name = 'VERSION'
if ENV.key?(env_name)
"#{env_name} - #{ENV[env_name]}"
else
"#{env_name} not set"
end
end
# return provided content type
get '/contenttype/?' do
request.env['CONTENT_TYPE']
end
post '/contenttype/?' do
request.env['CONTENT_TYPE']
end
put '/contenttype/?' do
request.env['CONTENT_TYPE']
end
delete '/contenttype/?' do
request.env['CONTENT_TYPE']
end
# return provided body
get '/body/?' do
request.body
end
post '/body/?' do
request.body
end
put '/body/?' do
request.body
end
delete '/body/?' do
request.body
end
# return provided body
get '/vary/:header_list' do
header_names = params['header_list'].split(',').map(&:strip)
key_names = header_names.map { |header| [header, 'HTTP_' + header.upcase.tr('-', '_')] }
header_strings = []
key_names.each do |header_array|
header_strings << if request.env[header_array[1]]
format('%<header>s: %<header_value>s', header: header_array[0], header_value: request.env[header_array[1]])
else
format('%<header>s: %<header_value>s', header: header_array[0], header_value: '<unavailable>')
end
end
halt 200, { 'Vary' => params['header_list'], 'Cache-Control' => 's-maxage=30' }, "Vary: #{params['header_list']} - Date: #{Time.now.rfc822} - #{header_strings.join(' - ')}"
end
# return requests http status code
get %r{/([0-9]{3})} do
status_code = params['captures'].first.to_i
halt status_code, { 'Content-Type' => 'text/plain' }, "returned #{status_code}"
end
# return requests http status code
get %r{/(fail|warn)-after/([0-9]+)} do
mode = params['captures'].first
timeout = params['captures'][1].to_i
fail_time = Time.now - (settings.start_time + timeout)
status_code = 200
if fail_time.positive?
# timeout run out
status_code = if mode == 'warn'
429
else
500
end
end
halt status_code, { 'Content-Type' => 'text/plain' }, "returned #{status_code}"
end
get %r{/sleep/([0-9.]+)} do
sleep_time = params['captures'].first.to_f
sleep sleep_time
sleep_time.to_s
end