This project is a RESTful API built with Go that provides user authentication and CRUD operations using MongoDB. It includes secure authentication using JWT, proper CORS handling, and is tested using Postman. The goal is to demonstrate how to build a scalable and secure REST API using Go and MongoDB.
- Go (Golang) – Main programming language
- MongoDB – Database for storing user data
- JWT (JSON Web Tokens) – For user authentication and session management
- CORS – To handle cross-origin resource sharing securely
- Postman – For testing API endpoints
mongo-rest-api/
├── main.go # Entry point of the application
├── db/
│ └── mongo.go # MongoDB connection setup
├── models/
│ └── user.go # User model definition
├── handlers/
│ ├── user.go # Handlers for user CRUD operations
│ ├── auth.go # Registration and login logic
│ └── jwt_middleware.go # JWT validation middleware
├── .env # Environment variables (e.g., DB URI, JWT secret)
├── .gitignore # Files and directories to ignore in Git
└── readme.md # This documentation file
A screenshot of the initial project structure.
Endpoint: POST /register
Payload:
{
"name": "Mazhar",
"email": "mazhar@example.com",
"password": "123456"
}Postman Screenshot:
Endpoint: POST /login
Payload:
{
"email": "mazhar@example.com",
"password": "123456"
}Response: Returns a JWT token
Postman Screenshot:
Once you get the token from /login, set it in Postman:
- Go to the Authorization tab
- Choose Bearer Token
- Paste the JWT token
Postman Screenshot:
All endpoints below require the JWT token in the Authorization header.
Payload:
{
"name": "John Doe",
"email": "john@example.com"
}Postman Screenshot:
Postman Screenshot:
Replace {id} with a valid MongoDB user ID.
Postman Screenshot:
Payload:
{
"name": "Updated Name",
"email": "updated@example.com"
}Postman Screenshot:
Postman Screenshot:
MONGO_URI=mongodb://localhost:27017
JWT_SECRET=your_jwt_secret_key
PORT=8080-
Clone the repository:
git clone https://github.com/yourusername/mongo-rest-api.git cd mongo-rest-api -
Set up
.envwith your environment values (DB URI, JWT secret, port). -
Install dependencies and run:
go run main.go








