gpt4 book ai didi

ruby - 如何在 webrick 服务器上执行代码

转载 作者:太空宇宙 更新时间:2023-11-03 16:50:45 25 4
gpt4 key购买 nike

我像这样启动一个 webrick 服务器:

dell@dev:/var/www/ruby$ ruby -run  -httpd. -p 5000

并将此代码放入abc.rb:

require 'webrick'

root = File.path '/tmp/public_html'
server = WEBrick::HTTPServer.new :Port => 5000, :DocumentRoot => root

trap 'INT' do server.shutdown end
server.start

ary = { "0"=>"fred", "1"=>10, "2"=>3.14, "3"=>"This is a string", "4"=>"last element", }
ary.each do |key, value|
puts "#{key} #{value}"
end

当我运行这段代码时,它会在浏览器上显示相同的代码

http://localhost:5000/abc.rb

如何查看这段代码的输出,我已经问过这个问题,但没有得到任何正确答案:(

这是正确的代码吗?我想知道这个,这段代码放在哪里

require 'webrick'

root = File.path '/tmp/public_html'
server = WEBrick::HTTPServer.new :Port => 5000, :DocumentRoot => root

trap 'INT' do server.shutdown end
server.start

如果有人给我一步一步的答案来运行这段代码,我非常感谢..我不明白答案:(如何做到这一点

最佳答案

来自documentation :

The easiest way to have a server perform custom operations is through WEBrick::HTTPServer#mount_proc. The block given will be called with a WEBrick::HTTPRequest with request info and a WEBrick::HTTPResponse which must be filled in appropriately:

server.mount_proc '/' do |req, res|
res.body = 'Hello, world!'
end

Remember that server.mount_proc must server.start.

所以:

require 'webrick'

root = File.path '/tmp/public_html'
server = WEBrick::HTTPServer.new :Port => 5000, :DocumentRoot => root

server.mount_proc '/abc.rb' do |req, res|
ary = { "0"=>"fred", "1"=>10, "2"=>3.14, "3"=>"This is a string", "4"=>"last element" }
res.body = ary.map do |key, value|
"#{key} #{value}"
end.join("\n")
end

trap 'INT' do server.shutdown end
server.start

此外,我相信启动 WebBrick 的正确方法是运行:

ruby abc.rb

关于ruby - 如何在 webrick 服务器上执行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22526768/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com