一個基於webrick 的簡單web伺服器

來源:互聯網
上載者:User

標籤:ruby   webrick   

使用ruby 內建的webrick 可以非常方便地實現一個web伺服器。


webrick.rb 基本代碼如下:

#!/usr/bin/env rubyrequire ‘webrick‘root = File.expand_path ‘html‘server = WEBrick::HTTPServer.new :Port => 8000, :DocumentRoot => roottrap ‘INT‘ do server.shutdown endserver.start


使用命令ruby webrick.rb 即可啟動一個監聽在8000連接埠的web伺服器,

根目錄在目前的目錄的子目錄html裡。代碼中的web根目錄也可以是一個絕對路徑。


在web根目錄中建立一個樣本html檔案,立馬可以看到效果。比如:

echo "hello world" > html/index.html


上面的網頁伺服器沒有日誌功能,所有日誌直接列印在console


可以稍加潤色一下,加上日誌功能,代碼如下:

#!/usr/bin/env rubyrequire ‘webrick‘#webrootroot = File.expand_path ‘html‘#access loglogfile = File.open ‘log/webrick.log‘, ‘a+‘access_log = [ [logfile, WEBrick::AccessLog::COMBINED_LOG_FORMAT], ]log = WEBrick::Log.new logfileserver = WEBrick::HTTPServer.new :Port => 8001, :DocumentRoot => root, :Logger => log, :AccessLog => access_logtrap ‘INT‘ do server.shutdown endserver.start





本文出自 “專註Linux 營運” 部落格,請務必保留此出處http://purplegrape.blog.51cto.com/1330104/1891413

一個基於webrick 的簡單web伺服器

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.