Skip to content

ericgarzagzz/http-server

Repository files navigation

Simple HTTP Server

Purpose Build a very straightforward http server in order to understand better how http really works under the hood. This is also because I want to learn a bit of C in the process, so it's very likely there's going to be a lot of bad code and weird patterns

Phase 1: Serve static HTML page

Build enough so that a static HTML content can be served through GET /. No multi-threads, nothing fancy

  • Create a server that can listen to HTTP requests and dumps the raw request into stdout
  • Read method, path, and HTTP version from request
  • Send a hard coded response with a 200 OK status and mock HTML
  • Read and parse headers from request
  • Minimal router: GET / returns HTML, POST /echo parses the request and sends back the body as the response. Any other route should come back as 404 Not Found
  • Keep the server running and processing requests

Phase 2: Make it technically correct

Improve correctness without turning this into a production server.

  • Detect end of headers using \r\n\r\n instead of naive splitting
  • Parse request only after full headers are received
  • Read body strictly based on Content-Length
  • Support request bodies larger than the initial buffer (multiple read() calls)
  • Add Content-Length header to all responses
  • Return 400 Bad Request for malformed request lines
  • Return 405 Method Not Allowed for unsupported methods
  • Run with sanitizers (ASan/LSan) and fix memory issues
  • Stop unnecessary strdup calls and parse request in-place when possible

Phase 3: Serve real static files

Serve files inside a www/ directory.

  • Serve files from a www/ directory (e.g. GET /index.html -> ./www/index.html)
  • Default route: GET / serves ./www/index.html
  • Return 404 Not Found when file does not exist
  • AddContent-Type support by extension
  • Prevent path traversal
  • Stream file contents to the socket (do not load entire file into memory)

About

A very straightforward http server

Resources

Stars

Watchers

Forks

Packages

 
 
 

Contributors