HTTP client---(HTTP GET/POST)---web server---(Environment variables/stdin)---CGI app
- For an HTTP GET request, web servers receive a query string from the client, then put it as Environment variable QUERY_STRING into the CGI app's process.
- For an HTTP POST request, web servers receive form data from the client, then write to the CGI app's standard input, and denote the data length by Environment variable CONTENT_LENGTH.
Below is a demonstration.
CGI app
As environment variables and standard input are used by any process, any application can work as a CGI app.
Below is a simple bash script CGI app that prints out HTTP GET/POST data.
$ cat ./cgi-bin/app.sh
#!/bin/bash
# http header
echo -n 'Cotent-Type: text/plain'
echo -ne '\r\n\r\n'
# http GET query string becomes cgi app's environment variable $QUERY_STRING
echo $QUERY_STRING
# http POST form data becomes input to cgi app's stdin
# the data length is saved in $CONTENT_LENGTH
if [[ ! -z $CONTENT_LENGTH ]]; then
read -n $CONTENT_LENGTH post_data
echo $post_data
fi
Web server
For simplicity, python's http.server module is used as our Web server.
$ python -m http.server --cgi 8000
HTTP client
Any web client works but here we use curl for demonstration.
$ curl --data 'form data or json' 'http://192.168.0.31:8000/cgi-bin/app.sh?x=2&y=2'
x=2&y=2
form data or json
No comments:
Post a Comment