0 CGI cheat-sheet
A CGI compatible Web Server App (e.g. Apache) handles all HTTP protocol, translates protocol text into simple key/value format strings, put them into a process's environment variables, then launch a program. This launched program runs any logic using the environment variables, writes output into the stdout stream which is connected to the Web Server App which then packs these outputs based on HTTP protocol and transfers them to the client (e.g. Chrome).
In one word, a Web Server App is a middleware that acts as a middle man between an HTTP client and a web application.
CGI is just one of many ways for a Web Server App communicates with a web program. Any program able to use standard input/output and environment variables can take advantage of CGI.
Be it a bash script, Perl script, Python script, pure C program, Java Program, CGI can serve it.
1 Apache CGI configuration
The default httpd.conf alreay has a line to configure CGI.
$ cat /etc/httpd/conf/httpd.conf | grep '^[[:space:]]*ScriptAlias'
ScriptAlias /cgi-bin/ "/var/www/cgi-bin/"
So, any executable under /var/www/cgi-bin/ can be a valid web app.
2 Python as a CGI application
$ cat /var/www/cgi-bin/test.py
#!/usr/bin/python3
print("Content-Type: text/plain")
print("") # This is a must due to HTTP protocol
print('Python script as a CGI web app')
Even Apache handles most of the HTTP protocol, your app still needs to deal with some protocol related things. Here, the real output must be separated by an empty line to the first "Content-Type:" line.
3 Test
$ curl http://127.0.0.1/cgi-bin/test.py
Python script as a CGI web app
No comments:
Post a Comment