A lightweight HTTP server built from scratch in Go using the net package. It handles basic routing, dynamic paths, query parameters, and concurrent request handling using goroutines.
- Routing: Matches HTTP requests to handlers based on URL patterns.
- Dynamic Paths: Captures path segments (e.g., /user/:name extracts name).
- Query Parameters: Parses query strings (e.g., /search?q=foo).
- POST Body Handling: Processes request bodies up to 64 KiB.
- Custom Headers: Supports adding headers like X-Foo: bar.
- HTTP/1.1 Keep-Alive: Handles persistent connections for multiple requests.
- Concurrent Connections: Uses goroutines for efficient request handling.
MiniHTTP leverages Go’s net package to manage TCP connections at a low level:
-
TCP Listener:
net.Listen("tcp", ":PORT")creates a TCP listener on a specific port to accept incoming connections.
-
Connection Handling:
Listener.Accept()retrieves incoming TCP connections (net.Conn), with each connection handled in a separate goroutine.- Each connection is processed in
handleConnection, which reads requests and writes responses.
-
Reading Requests:
- A
bufio.Readeronnet.Connreads raw HTTP request data (method, path, headers, body). ReadRequestparses the TCP stream into aRequeststruct, handling query params and body (up to 64 KiB).
- A
-
Writing Responses:
- The
simpleResponseWriterusesnet.Conn.Writeto send HTTP responses (status, headers, body). - Responses are formatted (e.g.,
HTTP/1.1 200 OK\r\n) and written to the TCP connection.
- The
-
Keep-Alive Support:
- Supports HTTP/1.1 persistent connections by checking the
Connectionheader, looping to handle multiple requests unless closed or HTTP/1.0 is used.
- Supports HTTP/1.1 persistent connections by checking the
-
Run:
go run main.go
Server starts on
:8080. -
Test Endpoints:
curl http://localhost:8080/→Hello servercurl http://localhost:8080/user/Alice→Hello, Alicecurl http://localhost:8080/search?q=foo→Search for: foocurl -X POST -d "test" http://localhost:8080/submit→Received: test