Welcome to KAI Backend, a comprehensive REST API designed for managing Indonesian Railway (Kereta Api Indonesia) ticket booking system. Built with Go, Fiber framework, and MongoDB, this backend service provides a fast, scalable, and efficient foundation for a railway ticket booking application. It follows modern API design principles with comprehensive JWT authentication, clean architecture, and robust data validation, making it highly maintainable and performant.
- 🔐 JWT Authentication — Secure endpoints using JSON Web Tokens (JWT) with Bearer token support, ensuring that only authenticated users can access protected resources.
- 🏗️ Clean Architecture — Organized into distinct layers (Handlers, Services, Repositories, Domain) for clear separation of concerns, making the codebase easy to understand, test, and scale.
- 📦 Full CRUD Operations — Comprehensive Create, Read, Update, and Delete functionality for all core entities:
- Users: Complete user management with secure bcrypt password hashing and JWT-based authentication.
- Stations: Manage railway stations with detailed information and geographic data.
- Trains: Train fleet management with carriage and seat configuration.
- Schedules: Route scheduling with origin-destination mapping and real-time availability.
- Bookings: Complete booking lifecycle from creation to payment tracking and cancellation.
- 🎫 Booking System — Core booking functionality with:
- Seat availability checking
- Automated booking code generation
- Basic booking status management
- 🔍 Schedule Search — Search schedules by origin, destination, and departure date.
- 🛡️ Request Validation — Built-in validation using Go validator with comprehensive error messages for data integrity.
- 🍃 MongoDB Integration — Utilizes MongoDB with official Go driver for flexible document-based data storage and efficient queries.
- 🚀 High Performance — Built on Fiber framework for automatic API documentation, middleware support, and blazing-fast HTTP performance.
- 📊 Interactive Documentation — Auto-generated Swagger/OpenAPI documentation with "Try it out" functionality.
- ⚙️ Centralized Configuration — Manages all environment-specific settings securely through environment variables with godotenv.
- 🔒 Security Middleware — CORS protection, request logging, and JWT middleware for comprehensive API security.
- User registers by sending their details to the
/api/auth/registerendpoint with email, password, and personal information. - User authenticates via
/api/auth/loginto receive JWT tokens for accessing protected endpoints. - User searches schedules by origin station, destination station, and departure date to find available trains.
- User creates booking by selecting a schedule and seat, the system checks availability and creates the booking.
- JWT Middleware validates tokens for protected endpoints and extracts user information.
- The system follows Clean Architecture: Handler → Service → Repository → Database for clear separation of concerns.
- MongoDB stores all data with proper indexing for efficient queries and data retrieval.
- Structured JSON responses with consistent error handling are returned to the client.
- 🐹 Go 1.21+ (Programming Language)
- ⚡ Fiber v2 (High-performance HTTP Framework)
- 🍃 MongoDB (NoSQL Database)
- 🔗 MongoDB Go Driver (Official Database Driver)
- 🔐 golang-jwt/jwt (JWT Implementation)
- 🛡️ bcrypt (Password Hashing)
- ✅ go-playground/validator (Data Validation)
- 📝 Swagger/OpenAPI (API Documentation)
- 🔄 godotenv (Environment Configuration)
- 🌐 CORS Middleware (Cross-Origin Resource Sharing)
- 📊 Request Logger (HTTP Request Logging)
- 🌐 Go Backend: View Code
- 📖 API Documentation:
http://localhost:8080/docs(when running locally)
Follow these steps to get KAI Backend up and running on your local machine.
- Go (version 1.21 or higher)
- MongoDB (Local installation or MongoDB Atlas)
- A tool to interact with your database (e.g., MongoDB Compass, Studio 3T, or MongoDB Shell)
-
Clone the repository:
git clone https://github.com/LouisFernando1204/kai-backend.git cd kai-backend -
Initialize Go modules:
go mod download
-
Set up environment variables:
- Create a
.envfile in the root directory. - Add the following configuration variables:
# Server Configuration SERVER_HOST=localhost SERVER_PORT=8080 # MongoDB Atlas Configuration MONGO_URI=mongodb+srv://username:[email protected]/?retryWrites=true&w=majority MONGO_DATABASE=kai_db # JWT Configuration JWT_KEY=your_super_secret_jwt_key_here_at_least_32_characters JWT_EXP=60
- Create a
-
Generate JWT Secret Key (Optional):
go run cmd/jwt_key_generator/main.go
Copy the generated key to your
.envfile asJWT_KEY. -
Set up the database:
- Start your MongoDB server (local) or ensure MongoDB Atlas cluster is running.
- The application will automatically connect to the database specified in
MONGO_URI. - Collections will be created automatically when first accessed.
-
Build and run the application:
# Development mode go run main.go # Or build and run go build -o kai-backend ./kai-backend
The server should now be running on
http://localhost:8080. -
Access API Documentation:
- Swagger UI:
http://localhost:8080/docs - Welcome Message:
http://localhost:8080/
- Swagger UI:
POST /api/auth/register- Register new user with email, password, and personal detailsPOST /api/auth/login- User login with email and password
GET /api/stations- Get all railway stationsGET /api/stations/{id}- Get station by IDPOST /api/stations- Create new station (Admin only)PUT /api/stations/{id}- Update station (Admin only)DELETE /api/stations/{id}- Delete station (Admin only)
GET /api/trains- Get all trainsGET /api/trains/{id}- Get train by IDPOST /api/trains- Create new train with carriages (Admin only)PUT /api/trains/{id}- Update train (Admin only)DELETE /api/trains/{id}- Delete train (Admin only)
GET /api/schedules/search- Search schedules by origin, destination, and departure dateGET /api/schedules/{id}- Get schedule by IDGET /api/schedules/{id}/seats- Get seat layout for scheduleGET /api/schedules- Get all schedules (Admin only)POST /api/schedules- Create new schedule (Admin only)PUT /api/schedules/{id}- Update schedule (Admin only)DELETE /api/schedules/{id}- Delete schedule (Admin only)
POST /api/bookings- Create new booking with seat selectionGET /api/bookings- Get current user's bookingsGET /api/bookings/{id}- Get booking by IDPATCH /api/bookings/{id}/status- Update booking statusPOST /api/bookings/{id}/cancel- Cancel booking
- 🧑💻 Louis Fernando : @LouisFernando1204