2015-04-23 48 views
0

嗨我需要能夠接收來自GitLab(body => JSON)的請求以及在同一端口上提供文件。我正在嘗試使用Webrick來達到這個目的。我可以分開做這些。在同一端口上使用Webrick服務文件和處理請求

文件服務解決方案我做的:

server = WEBrick::HTTPServer.new(:Port => 3030, :DocumentRoot => '/') 
server.start 

接收和處理JSON我做的:

server = WEBrick::HTTPServer.new(:Port => 3030, :DocumentRoot => '/') 
server.mount_proc '/' do | req, res | 
    Queue.new(req.body) 
end 

但我需要這個功能結合起來,是有辦法與使用WEBrick做到這一點?

+0

我愛@Anthony給了答案,但我不知道 - 爲什麼不使用框架呢? Rails,Sinatra和[Plezi](https://github.com/boazsegev/plezi)應該在Webrick用於併發環境(比如生產環境)時工作得更快 - 並且Sinatra和Plezi都應該如此簡單(如果不是那麼容易)實施... – Myst

+0

這是針對大數據流水線測試的內部CI實現,而不是面向客戶,我們希望它儘可能輕。 –

回答

2

是的,Webrick或任何HTTP服務器都可以。根據用戶想要執行的操作,將會有兩種不同的HTTP操作:1.)提供文件的GET請求或2.)處理某些JSON的POST請求。

這裏有一個簡單的例子來告訴你如何做到既:

class Server < WEBrick::HTTPServlet::AbstractServlet 
    def do_GET (request, response) 
     puts "this is a get request" 
    end 

    def do_POST (request, response) 
     puts "this is a post request who received #{request.body}" 
    end 
end 

server = WEBrick::HTTPServer.new(:Port => 3030) 

server.mount "/", Server 

trap("INT") { 
    server.shutdown 
} 

server.start 

一旦運行,你可以通過執行以下操作在一個單獨的終端窗口測試:

curl localhost:3030 

輸出:

this is a get request 
localhost - - [23/Apr/2015:06:39:20 EDT] "GET/HTTP/1.1" 200 0 
- ->/

要測試POST請求:

curl -d "{\"json\":\"payload\"}" localhost:3030 

輸出:

this is a post request who received {"json":"payload"} 
localhost - - [23/Apr/2015:06:40:07 EDT] "POST/HTTP/1.1" 200 0 
- ->/
+0

謝謝你,我在你的回答實際出現之前自己解決了這個問題,但我發現你的回答更加優雅。再次感謝你。 –

1

既然你提到的目的,是光的代碼庫,這裏是一盞燈,使用快速腳本Plezi framework ...

這將允許更容易的測試,我認爲(但我有偏見)。另外,Plezi在我的機器上比Webrick快(儘管它是一個純粹的ruby框架,不涉及機架或'c'擴展)。

require 'plezi' 

class MyController 
    def index 
     # parsed JSON is acceible via the params Hash i.e. params[:foo] 
     # raw JSON request is acceible via request[:body] 
     # returned response can be set by returning a string... 
     "The request's params (parsed):\n#{params}\n\nThe raw body:\n#{request[:body]}" 
    end 
end 

# start to listen and set the root path for serving files. 
listen root: './' 

# set a catch-all route so that MyController#index is always called. 
route '*', MyController 

(如果你正在運行從終端腳本,記得使用exit命令退出irb - 這將激活Web服務器)

相關問題