This project is a simple Todo API built using Golang, featuring CRUD operations to manage todo items. It leverages Gorilla Mux for routing and TheDevSaddam Renderer for JSON responses and templating. The API is designed to be minimal yet functional, supporting essential features like creating, updating, retrieving, and deleting todo items. Additionally, it includes graceful server shutdown handling and basic input validation.
- The API includes a basic homepage using an HTML template (
home.tpl). - The
homeHandlerfunction renders this template when a request is made to/.
The API provides full CRUD (Create, Read, Update, Delete) functionality:
- Endpoint:
POST /todo - Function:
createTodo - Request Body: JSON containing
title(string). - Response: Returns the created todo item with a unique
idandcreated_attimestamp. - Validation: The
titlefield is required.
- Endpoint:
GET /todo - Function:
fetchTodos - Response: Returns all todo items as a JSON array.
- Endpoint:
PUT /todo/{id} - Function:
updateTodo - Request Body: JSON containing updated
titleandcompletedstatus. - Response: Updates the todo item if found; returns an error if the ID is invalid.
- Endpoint:
DELETE /todo/{id} - Function:
deleteTodo - Response: Removes the specified todo item if found; returns an error if not found.
- Ensures that bad requests (e.g., missing title, incorrect JSON format) return meaningful error messages.
- Uses
http.StatusBadRequestfor invalid requests andhttp.StatusNotFoundfor missing todos.
- The server listens for
os.Interruptsignals and safely shuts down when triggered. - Uses
context.WithTimeout()to allow the server to finish ongoing requests before stopping.
- The
renderer.Renderinstance (rnd) is initialized in theinit()function. - It is used to render templates (
home.tpl) and return JSON responses.
- Uses
mux.NewRouter()to define API endpoints. - Registers handlers for different HTTP methods (GET, POST, PUT, DELETE).
- Uses an in-memory slice (
[]todo) to store todo items. - Each todo item contains:
ID(string) – Unique identifier based on timestamp.Title(string) – Task description.Completed(bool) – Task completion status.CreatedAt(time.Time) – Timestamp when the task was created.
- The server listens on port 9010.
- Uses
http.Serverwith timeouts for better performance and security. - Logs server start-up and shutdown events.
Ensure you have the following installed:
- Golang (1.16 or later)
- Git (for version control)
git clone <repository-url>
cd <project-folder>go mod tidygo run main.goThe server will start on http://localhost:9010.
You can use Postman or curl to test the endpoints:
curl -X POST "http://localhost:9010/todo" -H "Content-Type: application/json" -d '{"title":"Learn Golang"}'curl -X GET "http://localhost:9010/todo"curl -X PUT "http://localhost:9010/todo/{id}" -H "Content-Type: application/json" -d '{"title":"Updated Task", "completed":true}'curl -X DELETE "http://localhost:9010/todo/{id}"