/http-server

a simple http server

Primary LanguageC++

http-server

Brief

A simple HTTP server for learning purpose. It supports basic GET and POST methods, static file serving, thread pooling, LRU caching, and logging.

Prerequisites

  • spdlog (for logging)
  • oha (for concurrency testing)

Supported Features

  • GET Method

    • Basic GET: Get server files.
    • Echo Endpoint: Echoes the request details.
    • Static File Serving: Serve static files from the server directory.
  • POST Method

    • Echo Endpoint: Echoes the request details.
    • Upload Endpoint: Uploads content to a default text file.
  • Logging

  • LRU Caching

    • When a file is requested, check the cache first. If it exist, serve the file from cache, if not, load from disk and put it into cache.
    • Caches entries will expire if they are more than 1 minute old.
  • Thread Pooling

    • Use STL thread for managing threads.

How to build and run

mkdir build
cd build
cmake ..
make -j
./http-server

Usage Example

Basic GET method

Default (home.html)

curl http://localhost
  • The default URL of GET method is “home.html”

GET home.html

curl http://localhost:8080/home.html
  • Get server files (example: home.html)

Echo

curl http://localhost:8080/echo
  • The endpoint of echo in GET method

Static File Serving for GET method

Demo video on youtube

btw, I use Neovim and tmux. You can check out my configuration here.

Concurrency Test

Running a Concurrency Test

oha http://localhost:8080
  • Perform a concurrency test using oha

Demo video on youtube

Basic POST Method

Echo

curl -X POST http://localhost:8080/echo
  • The endpoint of echo in POST method

Upload data to the server.

curl -D - -X POST -H "Content-Type: text/plain" -d "Hello!" http://localhost:8080/upload
  • create "uploads/" directory (default).
  • write contents "Hello!" to "uploads/uploaded_file.txt"

File overview

  • include/cache.h, src/cache.cpp

    • LRU cache implementation.
  • include/file.h, src/file.cpp

    • file-related utilities.
  • include/log.h, src/log.cpp

  • include/net.h, src/net.cpp

    • Low-level networking code.
  • include/request.h, src/request.cpp

    • HTTP request handling.
  • include/response.h, src/response.cpp

    • HTTP response building.
  • include/server.h, src/server.cpp

    • HTTP server implementation.
  • include/thread_pool.hpp

    • thread pool implementation (using .hpp for template code).

Reference