⚠️ This is NOT A PRODUCTION PROJECT. It's a personal project I'm building to practice and become proficient in Go
A minimal HTTP server implemented using Go’s net/http package. Implemented to understand how handlers, middleware, concurrency, and context propagation work in Go.
-
/health: Returns OK if server is running. -
/stats: endpoint that returns the request metrics like total requests, successful requests and Unauthorized requests in JSON. -
/work: endpoint that simulates a CPU bound work with context cancellation. Server stops computation immediately when the client disconnects. It also has an optional query "limit=" to set the number of computations that must be performed.
For examplehttp://localhost:4000/work?limit=1000will compute the first 1000 prime numbers. -
/upload: Recieves the file in the POST request form field. Creates a temporary file with a unique name in the./uploadsdirectory usingos.CreateTempand copies the file to it usingio.Copy(). Renames the temp file using os.Rename() with a safe name created by a helper method in the format./uploads/uuid_originalFileName.extension.uuidis a unique ID generated bygoogle/uuidto maintain unique file names. Performs clean up when the function returns. -
/download: Recieves the file name from the incoming request'sfilequery. Checks if the file exists, usingos.Stat(). If the file exists, it useshttp.ServeFile()to send the file to the client.
-
AuthMiddleware(): protects the endpoints and returns 401 if the Basic Auth credentials are invalid. The password has been hardcoded because this is just a practice/learning project and I wanted to focus on other important concepts such as file uploading and downloading. -
LoggingMiddleware(): logs the request's method, path, timestamp and time taken to complete the request. -
StatsMiddleware(): the outermost middleware that checks the request's status code and updates the in-memory counters usingatomic.AddInt64()to keep track of the metrics. -
MaxBodySize(): Limits the incoming request's body size to 50 << 20 bytes in order to prevent DoS
net/httpcontextsync/atomicpath/filepathencoding/jsongithub.com/google/uuidstrconvregexpstringsosiotimelog
- Clone Repository
git clone https://github.com/aDiThYa-808/golang-http-server.git- Start server
go run ./cmd/server- Upload file
curl -X POST http://localhost:4000/upload -F "file=@example.pdf"- Download file
curl -o output.pdf http://localhost:4000/download?file=example.pdf- View metrics
curl -u admin:pass http://localhost:4000/statsNote: the password is hardcoded only because this project was made for learning purpose.
- Simulate work(compute prime numbers)
curl http://localhost:4000/work?limit=50000- Health check
curl -u admin:pass http://localhost:4000/health