Lihtsaid cgi programminäiteid
proov.sh on shelli skript, mis trükib välja serverile saadetud info:
#!/bin/sh echo 'Content-type: text/html' echo echo echo 'tere tali' echo '<p>' echo $QUERY_STRING
proov.py on pythoni programm, mis parsib serverile saadetud info (cgi protokolli järgi), trükib argumendid ja liidab nende väärtused kokku:
#!/usr/bin/python
import string, os, cgi, sys, tempfile, traceback
import cgitb;
def main():
print 'content-type: text/html\n\n'
print '<h2>Väike näide</h2>'
cgitb.enable()
form = cgi.FieldStorage()
sum=0
for key in form.keys():
val=form[key].value
print key,' võrdub ',val
print '<br>'
sum=sum+int(val)
print '<p>'
print '<b>summa on: ',sum,'</b>'
return
main()
adder.c on C-s kirjutatud rakendus, mis parsib kaks argumenti (eeldades ampersandi eraldajaks ja nimede puudumist!) ja liidab nad kokku. Mingeid teeke peale standardse ei kasutata.
/*
* adder.c - a minimal CGI program that adds two numbers together
*/
/* $begin adder */
#include "csapp.h"
int main(void) {
char *buf, *p;
char arg1[MAXLINE], arg2[MAXLINE], content[MAXLINE];
int n1=0, n2=0;
/* Extract the two arguments */
if ((buf = getenv("QUERY_STRING")) != NULL) {
p = strchr(buf, '&');
*p = '\0';
strcpy(arg1, buf);
strcpy(arg2, p+1);
n1 = atoi(arg1);
n2 = atoi(arg2);
}
/* Make the response body */
sprintf(content, "Welcome to add.com: ");
sprintf(content, "%sTHE Internet addition portal.\r\n<p>", content);
sprintf(content, "%sThe answer is: %d + %d = %d\r\n<p>",
content, n1, n2, n1 + n2);
sprintf(content, "%sThanks for visiting!\r\n", content);
/* Generate the HTTP response */
printf("Content-length: %d\r\n", strlen(content));
printf("Content-type: text/html\r\n\r\n");
printf("%s", content);
fflush(stdout);
exit(0);
}
/* $end adder */