This is a RESTful API for user management, including authentication and authorization. The API is built with Go, uses PostgreSQL as the database, and JSON Web Tokens (JWT) for secure authentication.
- User registration
- User login with JWT token generation
- JWT-based authentication and authorization
- User profile retrieval (protected route)
- Go installed on your machine
- PostgreSQL installed and running
- Clone the repository:
git clone https://github.com/yourusername/microservice-user.git
cd user-management-api
- Install dependencies:
go mod tidy
- Create a .env file in the root directory with the following content:
JWT_SECRET_KEY=your_generated_secret_key
DB_HOST=localhost
DB_USER=youruser
DB_NAME=yourdb
DB_PASSWORD=yourpassword
DB_PORT=5432
- Run PostgreSQL and create the database:
CREATE DATABASE yourdb;
- Update the config/config.go file with your PostgreSQL credentials if needed:
dsn := "host=localhost user=youruser dbname=yourdb sslmode=disable password=yourpassword"
- Run the application:
go run main.go
The API will be available at http://localhost:8080
.
Register User
-
URL:
/register
-
Method:
POST
-
Request Body:
{ "username": "yourusername", "password": "yourpassword" }
-
Response:
-
201 Created
{ "message": "User registered successfully" }
-
Login User
-
URL:
/login
-
Method:
POST
-
Request Body:
{ "username": "yourusername", "password": "yourpassword" }
-
Response:
-
200 OK
{ "token": "your.jwt.token" }
-
401 Unauthorized
{ "error": "Invalid username or password" }
-
- URL:
/auth/profile
- Method:
GET
- Headers:
Authorization: Bearer your.jwt.token
- Response:
200 OK
{ "message": "Authenticated", "username": "yourusername" }
401 Unauthorized
{ "error": "Unauthorized" }
This project is licensed under the MIT License.
- Gin (web framework)
- GORM (ORM)
- JWT (JSON Web Tokens)
- godotenv (environment variables)
José Henrique |