2012-11-08 81 views
0

我得到從UDP套接字如下回應:UDP HTTP頭解析Ruby中

HTTP/1.1 200 OK 
CACHE-CONTROL: max-age=1800 
DATE: Thu, 08 Nov 2012 12:32:33 GMT 
EXT: 
LOCATION: http://192.168.0.100:49153/nmrDescription.xml 
SERVER: Windows2000/0.0 UPnP/1.0 PhilipsIntelSDK/1.4 DLNADOC/1.50 
X-User-Agent: redsonic 
ST: upnp:rootdevice 
USN: uuid:F00DBABE-SA5E-BABA-DADA188ED55ED539::upnp:rootdevice 

有一個圖書館,或簡單的方法來解析這一切呢?

我想獲得像下面這樣:

{ 
    :cache_control => "max-age=1800" 
    :date => "Thu, 08 Nov 2012 12:32:33 GMT" 
    :ext => nil 
    :location => "http://192.168.0.100:49153/nmrDescription.xml" 
    # Etc. 
} 

回答

1
response.split($/).drop(1).inject({}) do |h, l| 
    k, v = l.split(": ", 2) 
    h[k.downcase.gsub("-", "_").to_sym] = (v unless v.empty?) 
    h 
end 

# => { 
# :cache_control=>"max-age=1800", 
# :date=>"Thu, 08 Nov 2012 12:32:33 GMT", 
# :ext=>nil, 
# :location=>"http://192.168.0.100:49153/nmrDescription.xml", 
# :server=>"Windows2000/0.0 UPnP/1.0 PhilipsIntelSDK/1.4 DLNADOC/1.50", 
# :x_user_agent=>"redsonic", 
# :st=>"upnp:rootdevice", 
# :usn=>"uuid:F00DBABE-SA5E-BABA-DADA188ED55ED539::upnp:rootdevice" 
#} 
+0

不錯,我希望一個簡單的標準功能/解析器,但這會做得很好!謝謝! –