Skip to content

Commit

Permalink
Update example
Browse files Browse the repository at this point in the history
  • Loading branch information
hfm committed Mar 28, 2018
1 parent 52ac54c commit ec75d1a
Showing 1 changed file with 27 additions and 76 deletions.
103 changes: 27 additions & 76 deletions example/server.rb
@@ -1,82 +1,33 @@
#
# Server Configration
#

server = SimpleHttpServer.new({

:server_ip => "0.0.0.0",
:port => 8000,
:document_root => "./",
:debug => true,
})


#
# HTTP Initialize Configuration Per Request
#

# You can use request parameters at http or location configration
# r.method
# r.schema
# r.host
# r.port
# r.path
# r.query
# r.headers
# r.body

server.http do |r|
server.set_response_headers({
"Server" => "my-mruby-simplehttpserver",
"Date" => server.http_date,
})
end

#
# Location Configration
#

# /mruby location config
server.location "/mruby" do |r|
if r.method == "POST"
server.response_body = "Hello mruby World. Your post is '#{r.body}'\n"
else
server.response_body = "Hello mruby World at '#{r.path}'\n"
app = Proc.new do |env|
code = 200
headers = { 'Server' => 'mruby-simplehttpserver' }
path = env['PATH_INFO']
method = env['REQUEST_METHOD']
body = nil

case path
when '/mruby'
body = "Hello mruby World.\n"
when "/html"
headers['Content-type'] = 'text/html; charset=utf-8'
body = "<H1>Hello mruby World.</H1>\n"
when "/notfound"
# Custom error response message
body = "Not Found on this server: #{path}\n"
code = 404
end
server.response_body += r.inspect + "\n"
server.create_response
end

# /mruby/ruby location config, location config longest match
server.location "/mruby/ruby" do |r|
server.response_body = "Hello mruby World. longest matche.\n"
server.create_response
end

server.location "/html" do |r|
server.set_response_headers "Content-type" => "text/html; charset=utf-8"
server.response_body = "<H1>Hello mruby World.</H1>\n"
server.create_response
[code, headers, [body]]
end

# Custom error response message
server.location "/notfound" do |r|
server.response_body = "Not Found on this server: #{r.path}\n"
server.create_response 404
end

# Static html file contents
server.location "/static/" do |r|
if r.method == 'GET' && r.path.is_dir? || r.path.is_html?
filename = server.config[:document_root] + r.path
filename += r.path.is_dir? ? 'index.html' : ''

server.set_response_headers "Content-Type" => "text/html; charset=utf-8"
server.file_response r, filename
else
server.response_body = "Service Unavailable\n"
server.create_response 503
end
end
#
# Server Configration
#
server = SimpleHttpServer.new(
server_ip: 'localhost',
port: 8000,
debug: true,
app: app,
)

server.run

0 comments on commit ec75d1a

Please sign in to comment.