A complete authentication system built with Go, featuring user registration, login, logout, and JWT token-based authentication with PostgreSQL database. The project follows clean architecture principles with a well-organized folder structure.
awesomeProject/
βββ internal/
β βββ auth/ # Authentication logic (JWT, password hashing)
β βββ config/ # Configuration management
β βββ database/ # Database operations and connection
β βββ handlers/ # HTTP request handlers
β βββ models/ # Data structures and types
β βββ routes/ # Route definitions and middleware
βββ main.go # Application entry point
βββ go.mod # Go module dependencies
βββ Dockerfile # Docker containerization
βββ docker-compose.yml # Docker Compose for development
βββ Makefile # Build and development commands
βββ .dockerignore # Docker build exclusions
βββ test_api.http # API testing requests
βββ README.md # Project documentation
- β Clean Architecture - Well-organized code structure
- β User Registration - Create new accounts with username, email, and password
- β Secure Password Hashing - Bcrypt encryption for security
- β JWT Authentication - Secure token-based authentication
- β User Login/Logout - Complete authentication flow
- β Protected Routes - Middleware for secure endpoints
- β PostgreSQL Integration - Full database support
- β Input Validation - Comprehensive error handling
- β Docker Support - Containerized deployment
- β Environment Configuration - Flexible configuration management
-
Clone and navigate to the project:
cd awesomeProject -
Start the application with Docker Compose:
docker-compose up --build
This will start both PostgreSQL and the Go API automatically.
-
Test the API:
curl http://localhost:8080/health
-
Install dependencies:
make deps # or go mod tidy -
Set up PostgreSQL database:
make db-setup
Then create the database manually:
CREATE DATABASE auth_db; CREATE USER postgres WITH PASSWORD 'password'; GRANT ALL PRIVILEGES ON DATABASE auth_db TO postgres;
-
Create environment file:
# Create .env file with your configuration echo "DATABASE_URL=postgres://postgres:password@localhost:5432/auth_db?sslmode=disable" > .env echo "JWT_SECRET=your-super-secret-jwt-key-change-this-in-production" >> .env
-
Run the application:
make run # or go run main.go
The project includes a Makefile with useful commands:
make help # Show all available commands
make deps # Install dependencies
make run # Run the application
make build # Build the application
make test # Run tests
make clean # Clean build artifacts
make lint # Run linter
make docker # Build Docker image
make docker-run # Run with Docker- POST
/api/register - Body:
{ "username": "john_doe", "email": "john@example.com", "password": "securepassword123" }
- POST
/api/login - Body:
{ "username": "john_doe", "password": "securepassword123" }
- GET
/health
Note: All protected endpoints require the Authorization header with the JWT token.
- POST
/api/logout - Headers:
Authorization: Bearer <token>
- GET
/api/profile - Headers:
Authorization: Bearer <token>
Use the provided test_api.http file with VS Code REST Client or similar tools:
# Test health endpoint
curl http://localhost:8080/health
# Register a new user
curl -X POST http://localhost:8080/api/register \
-H "Content-Type: application/json" \
-d '{
"username": "testuser",
"email": "test@example.com",
"password": "password123"
}'
# Login
curl -X POST http://localhost:8080/api/login \
-H "Content-Type: application/json" \
-d '{
"username": "testuser",
"password": "password123"
}'internal/models/- Data structures and request/response typesinternal/database/- Database connection and operationsinternal/auth/- JWT token management and password hashinginternal/handlers/- HTTP request handlersinternal/routes/- Route definitions and middleware setupinternal/config/- Configuration and environment management
- Models - Define data structures for users, requests, and responses
- Database - Handle all database operations with proper error handling
- Auth - Manage JWT tokens, password hashing, and authentication middleware
- Handlers - Process HTTP requests and return appropriate responses
- Routes - Define API endpoints and apply middleware
- Config - Manage environment variables and configuration
- Password Hashing - Bcrypt with default cost
- JWT Tokens - Secure token-based authentication with 24-hour expiration
- Input Validation - Comprehensive validation for all user inputs
- SQL Injection Protection - Parameterized queries
- Environment Variables - Sensitive configuration stored securely
The application automatically creates the following table:
CREATE TABLE users (
id SERIAL PRIMARY KEY,
username VARCHAR(50) UNIQUE NOT NULL,
email VARCHAR(100) UNIQUE NOT NULL,
password_hash VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);# Build the image
docker build -t auth-api .
# Run the container
docker run -p 8080:8080 --env-file .env auth-api# Start all services
docker-compose up --build
# Stop all services
docker-compose down
# View logs
docker-compose logs -f auth-api| Variable | Description | Default |
|---|---|---|
DATABASE_URL |
PostgreSQL connection string | postgres://postgres:password@localhost:5432/auth_db?sslmode=disable |
JWT_SECRET |
Secret key for JWT signing | your-secret-key |
postgres://username:password@host:port/database_name?sslmode=disable
- Change JWT Secret - Use a strong, unique secret key
- Database Security - Use SSL connections and strong passwords
- HTTPS - Always use HTTPS in production
- Rate Limiting - Implement rate limiting for auth endpoints
- Token Blacklisting - Implement token blacklisting for logout
- Logging - Add comprehensive logging
- Monitoring - Add health checks and monitoring
# Production environment variables
export DATABASE_URL="postgres://user:password@host:5432/dbname?sslmode=require"
export JWT_SECRET="your-production-secret-key"-
Database Connection Error
- Ensure PostgreSQL is running
- Check connection string in
.envfile - Verify database credentials
-
Port Already in Use
- Change port in code or kill existing process
- Use different port with Docker:
-p 8081:8080
-
Missing Dependencies
- Run
make depsorgo mod tidy
- Run
-
Docker Issues
- Ensure Docker and Docker Compose are installed
- Check if ports are available
- Use
docker-compose logsto debug
This project is open source and available under the MIT License.