64 lines
1.9 KiB
C
64 lines
1.9 KiB
C
/*
|
|
* cgi-bin/add.c — 简单CGI加法计算器
|
|
*
|
|
* 用于测试Web服务器的CGI功能
|
|
* GET: /cgi-bin/add?a=10&b=20
|
|
* POST: 提交表单到 /cgi-bin/add
|
|
*/
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <unistd.h>
|
|
|
|
int main(void)
|
|
{
|
|
char *query = getenv("QUERY_STRING");
|
|
char *method = getenv("REQUEST_METHOD");
|
|
|
|
printf("Content-Type: text/html; charset=UTF-8\r\n\r\n");
|
|
printf("<!DOCTYPE html>\n<html><head>\n");
|
|
printf("<meta charset=\"UTF-8\">\n");
|
|
printf("<title>CGI Calculator</title>\n");
|
|
printf("<style>body{font-family:Arial;margin:40px;}"
|
|
"h1{color:#2a7;}.result{background:#f5f5f5;padding:20px;"
|
|
"border-radius:10px;font-size:1.5em;text-align:center;}"
|
|
"a{color:#667eea;}</style>\n");
|
|
printf("</head><body>\n");
|
|
printf("<h1>🔧 CGI 动态计算器 (实验4)</h1>\n");
|
|
|
|
/* 从 stdin 读取 POST 数据 */
|
|
char post_data[1024] = "";
|
|
if (method && strcmp(method, "POST") == 0) {
|
|
char *len_str = getenv("CONTENT_LENGTH");
|
|
if (len_str) {
|
|
int len = atoi(len_str);
|
|
if (len > 0 && len < (int)sizeof(post_data) - 1) {
|
|
fread(post_data, 1, len, stdin);
|
|
post_data[len] = '\0';
|
|
}
|
|
}
|
|
query = post_data;
|
|
}
|
|
|
|
/* 解析参数 a 和 b */
|
|
int a = 0, b = 0;
|
|
if (query) {
|
|
char *pa = strstr(query, "a=");
|
|
char *pb = strstr(query, "b=");
|
|
if (pa) a = atoi(pa + 2);
|
|
if (pb) b = atoi(pb + 2);
|
|
}
|
|
|
|
printf("<div class=\"result\">\n");
|
|
printf("<p>%d + %d = <strong>%d</strong></p>\n", a, b, a + b);
|
|
printf("<p>Method: %s | PID: %d</p>\n",
|
|
method ? method : "UNKNOWN", getpid());
|
|
printf("</div>\n");
|
|
|
|
printf("<p><a href=\"/\">← 返回首页</a></p>\n");
|
|
printf("<hr><em>Experiment4 CGI v1.0</em>\n");
|
|
printf("</body></html>\n");
|
|
|
|
return 0;
|
|
}
|