Getting Started with C: Build a Tiny HTTP Server (Chinese‑Annotated Version)
This guide walks C beginners through the TinyHttp project—providing Chinese annotations, environment setup, common pitfalls, detailed code flow, key function explanations, and step‑by‑step instructions to compile, run, and test a minimal web server.
Overview
TinyHttp is a minimal web server written in 1999 by J. David Blackstone for a class assignment. It supports static page browsing and CGI execution. This fork adds Chinese annotations to httpd.c and simpleclient.c, and introduces two helper functions— request_write and response_read —to simulate HTTP GET requests.
Repository
https://github.com/gofish2020/Tinyhttp
Environment Setup
Install a C development and debugging toolchain (e.g., gcc, make). Reference: https://zhuanlan.zhihu.com/p/571934657?utm_id=0
Verify Perl installation: which perl Expected output like /usr/bin/perl.
Install the Perl‑CGI module via CPAN:
perl -MCPAN -e shell
cpan[1]> install CGI.pm
perl -MCGI -e 'print "CGI.pm version $CGI::VERSION
";'Expected output: CGI.pm version 4.48.
Common Pitfalls
In check.cgi and color.cgi the shebang line #!/usr/bin/perl -Tw must match the actual Perl path on the system.
Make the CGI scripts executable:
chmod a+x check.cgi
chmod a+x color.cgiCode Flow
Program entry at main. startup binds the IP address and port, then starts listening.
Each incoming connection spawns a thread; the callback accept_request processes the HTTP request. get_line reads a line from the socket using \r\n as delimiter and parses the request line to identify the target file.
If the target is a directory, serve_file serves the static file.
If the target is a CGI script, execute_cgi runs the script.
Key Functions
get_line reads until the \r\n sequence, reflecting the HTTP packet format.
Example request line:
GET /user?id=1&country=china HTTP/1.1execute_cgi creates a pipe, forks, and redirects STDIN/STDOUT to run the CGI program.
Demo Procedure
Compile the source: make Start the server: ./httpd Open a browser and navigate to http://127.0.0.1:4000.
Enter a color value (e.g., red) and submit; the CGI script returns the response.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Nullbody Notes
Go backend development, learning open-source project source code together, focusing on simplicity and practicality.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
