2011/05/02

CGI

有時候,想要瞭解某些協定、標準,最準確也最快速的方法就是直接去讀它的 RFC 文件。
應該也不用讀太多,每條協定幾乎都有摘要(Abstract)跟它的存在目的(Purpose)。

這篇是我對 Common Gateway Interface 的筆記。
先節錄幾段 Wikipedia 與 RFC 3875 的內容:

" The Common Gateway Interface (CGI) is a standard (RFC 3875: CGI Version 1.1) that defines how web server software can delegate the generation of web pages to a text-based application. Such applications are known as CGI scripts; they can be written in any programming language, although scripting languages are often used. " - Wikipedia

" The Common Gateway Interface (CGI) is a simple interface for running external programs, software or gateways under an information server in a platform-independent manner. Currently, the supported information servers are HTTP servers. " - RFC 3875

" The Common Gateway Interface (CGI) allows an HTTP server and a CGI script to share responsibility for responding to client requests. " - RFC 3875

" The server is responsible for managing connection, data transfer, transport and network issues related to the client request, whereas the CGI script handles the application issues, such as data access and document processing. " - RFC 3875

簡單來說,「HTTP 伺服器」負責管理來自 Client 端的連線、傳輸等網路協定的相關事宜。
「HTTP 伺服器」會呼叫並執行「CGI 程式」,「CGI 程式」負責處理應用程式面的事宜,
例如,Client 端要求的檔案,是否需要經過處理,是否需要存取資料庫等等。

「CGI 程式」允許使用許多不同的程式語言來實作。
但那麼多種程式語言,「HTTP 伺服器」如果呼叫某種語言的「CGI 程式」,
就得有對應該程式語言的呼叫介面,那「HTTP 伺服器」的開發人員會瘋掉。

所以「CGI」就出現了。

「CGI」規範了「HTTP 伺服器」與「CGI 程式」間的連接。
「CGI」是包在「HTTP 伺服器」裡面的。

如果想要用某種程式語言撰寫「CGI 程式」供「HTTP 伺服器」叫用,
該程式語言必須有遵守「CGI」規範的接口。
在實際的例子中,這些接口就是 Apache 伺服器上的:
mod_php、mod_python、mod_ruby、mod_perl、mod_mono 等等。

「HTTP 伺服器」只要提供一套「CGI」規範給各種程式語言遵循即可,
而各種程式語言如何去實作「CGI」規範的接口,就是它自己的事了。

通常,Client 端送來的參數跟 URL 其實就是在呼叫要執行的「CGI 程式」了。

我畫了一張簡圖,希望大家指正:




【WSGI】

" WSGI (Web Server Gateway Interface) was created as a low-level interface between web servers and web applications or frameworks to promote common ground for portable web application development. WSGI is based on the existing CGI standard. " - Wikipedia

Python 的 WSGI,應該是欲取代掉 mod_python 的角色。
同一種程式語言,但該語言的多種框架如果對應到多種不同的「HTTP 伺服器」,還是很累人。
早先 Python 爲了迎合 CGI、FastCGI、mod_python 等不同規範,吃了不少苦頭。

但實際應用上,WSGI 沒那麼簡單。
WSGI 還可以起到 Middleware 的作用,可以看成是伺服器 response 內容的 filter。

這篇寫得很精彩:http://blog.ez2learn.com/2010/01/27/introduction-to-wsgi/



【Rack】

" Rack provides a minimal, modular and adaptable interface for developing web applications in Ruby. By wrapping HTTP requests and responses in the simplest way possible, it unifies and distills the API for web servers, web frameworks, and software in between (the so-called middleware) into a single method call. " - Wikipedia

在 Ruby 方面,受 WSGI 的啓發產生了 Rack。

" Rack 的規範非常簡單:就是需要一個 Call method 吃進一個 Enviroment 參數,然後回傳一個 Array,Array 裡面包含 status,header,body。" - XDite

請參考:http://blog.xdite.net/?p=1557

Reference:
01. http://en.wikipedia.org/wiki/Common_Gateway_Interface
02. http://tools.ietf.org/html/rfc3875
03. http://en.wikipedia.org/wiki/Web_Server_Gateway_Interface

沒有留言:

張貼留言