This is a sample CRUD service built with Golang, demonstrating a layered architecture that separates concerns into handler, service, repository, and model layers. The project uses TiDB as the relational database, Redis for caching
and async tasks
in-memory operations, and JWT for authentication.
Build a sample CRUD service API with Golang to showcase code structure and common best practices in web API development.
- Golang — Core programming language
- Fiber — Fast HTTP router
- GORM — ORM for database operations
- TiDB — Distributed SQL database
- Validator — Input validation
- Copier — Object copying for DTOs
- Redis — Distributed In-memory data caching
- Redis Stream — Background task queue using consumer group
- JWT — JSON Web Token implementation for authentication
├── cmd/
│ └── app/
│ └── main.go # Application entry point
├── pkg/ # Shared package configure
│ ├── crypto/
│ │ ├── aes.go # Advanced Encryption Standard
│ │ └── bcrypt.go # Bcrypt hashing
│ ├── redis/
│ │ └── redis.go # Redis configuration
│ └── db/
│ └── db.go # DB configuration
├── api/
│ ├── auth/
│ │ ├── routes.go # User authenticate-related endpoints
│ │ └── handler.go # Logic for handling auth API requests
│ └── student/
│ ├── routes.go # Student-related endpoints
│ └── handler.go # Logic for handling student API requests
├── internal/
│ ├── middleware/ # HTTP middleware (e.g., auth, rate limit, logging)
│ ├── repository/ # Data access layer (calls GORM & queries DB)
│ ├── service/ # Business logic, called from handler
│ ├── model/ # Database models/entities
│ └── dto/ # DTOs for transforming request/response data
- Layered Architecture: Divides the project into clear layers for maintainability and scalability.
- Goroutines: Background task workers use
goroutines
to run concurrentredis stream
jobs efficiently. - Rate Limit: Failed attempts and request limited using
redis
to prevent abuse429 Too Many Requests
. - DTO Pattern: Uses
copier
to map between internal models and request/response structures. - Validation: Ensures request payloads are validated with
go-playground/validator
. - ORM: Leverages
GORM
to interact withTiDB
in a concise and type-safe way. - SMTP: Standard
net/smtp
package for email sending to SMTP server.
💡 Tip: If you're using Gmail SMTP: allow "Less secure apps" (not recommended)
-
Configure Environment Create a
.env
file. find in a.env.example
file for environment:- Redis connection
- TiDB connection
- Email configure
- JWT Secret key
-
Run the App
go run cmd/app/main.go
-
Build the App
GOOS=linux GOARCH=amd64 go build -o bin/app ./cmd/app
-
Containerize the App
docker compose up -d
- Add unit tests and integration tests
- Add Swagger/OpenAPI documentation
This project is open-source and available under the MIT License.