{"id":39998426,"url":"https://github.com/deepraj02/backend-starter-golang","last_synced_at":"2026-01-19T01:31:27.231Z","repository":{"id":298834572,"uuid":"997832350","full_name":"deepraj02/backend-starter-golang","owner":"deepraj02","description":"A Template for Backend Projects in Go","archived":false,"fork":false,"pushed_at":"2025-09-28T07:00:33.000Z","size":104,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"master","last_synced_at":"2025-10-20T06:56:15.155Z","etag":null,"topics":["authentication","golang","gothic","jwt-authentication","oauth2","postgresql","redis","resend","template"],"latest_commit_sha":null,"homepage":"","language":"HTML","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/deepraj02.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-06-07T09:28:26.000Z","updated_at":"2025-09-28T07:02:09.000Z","dependencies_parsed_at":"2025-09-26T21:07:21.964Z","dependency_job_id":"668f0de6-364b-4db5-b731-eaad88a2d389","html_url":"https://github.com/deepraj02/backend-starter-golang","commit_stats":null,"previous_names":["deepraj02/backend-starter-golang"],"tags_count":0,"template":true,"template_full_name":null,"purl":"pkg:github/deepraj02/backend-starter-golang","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/deepraj02%2Fbackend-starter-golang","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/deepraj02%2Fbackend-starter-golang/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/deepraj02%2Fbackend-starter-golang/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/deepraj02%2Fbackend-starter-golang/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/deepraj02","download_url":"https://codeload.github.com/deepraj02/backend-starter-golang/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/deepraj02%2Fbackend-starter-golang/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28557057,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-19T00:46:33.223Z","status":"ssl_error","status_checked_at":"2026-01-19T00:46:32.754Z","response_time":98,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["authentication","golang","gothic","jwt-authentication","oauth2","postgresql","redis","resend","template"],"created_at":"2026-01-19T01:31:26.261Z","updated_at":"2026-01-19T01:31:27.222Z","avatar_url":"https://github.com/deepraj02.png","language":"HTML","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Go PostgreSQL Authentication Service\n\nA production-ready Go web application with complete authentication system, featuring user registration, login, forgot password functionality with email verification, Redis caching, and PostgreSQL database integration.\n\n## 🚀 Features\n\n### Core Features\n- **Clean Architecture**: Well-organized project structure following Go best practices\n- **PostgreSQL Integration**: Robust database connectivity with connection pooling\n- **Redis Caching**: Fast in-memory caching for reset codes and session management\n- **Database Migrations**: Automated schema management using Goose\n- **Docker Support**: Easy development setup with Docker Compose\n- **JSON API**: RESTful API with proper JSON response handling\n- **Logging**: Structured logging throughout the application\n- **Hot Reload**: Development server with Air for automatic reloading\n\n### Authentication Features\n- **User Registration**: Secure user account creation with password hashing\n- **User Login**: JWT-based authentication with access and refresh tokens\n- **User Profile**: Protected endpoint to retrieve user information\n- **Forgot Password**: Email-based password reset with 6-digit verification codes\n- **Password Reset**: Secure password update with code verification\n- **Email Service**: Integrated Resend email service for transactional emails\n- **Rate Limiting**: Redis-based reset code expiration (15 minutes)\n\n### Security Features\n- **Password Hashing**: bcrypt-based secure password storage\n- **JWT Tokens**: Access and refresh token implementation\n- **Input Validation**: Comprehensive request validation\n- **Protected Routes**: Middleware-based route protection\n- **Code Expiration**: Automatic cleanup of expired reset codes\n\n## 📋 Prerequisites\n\nBefore running this project, make sure you have the following installed:\n\n- [Go](https://golang.org/dl/) (version 1.24.0 or later)\n- [Docker](https://www.docker.com/get-started)\n- [Docker Compose](https://docs.docker.com/compose/install/)\n- [Air](https://github.com/air-verse/air) (for hot reload during development)\n- [Resend Account](https://resend.com/) (for email service)\n\n## 🛠️ Installation\n\n1. **Clone the repository**\n   ```bash\n   git clone https://github.com/deepraj02/go-postgres-starter.git\n   cd backend-auth\n   ```\n\n2. **Install Go dependencies**\n   ```bash\n   go mod download\n   ```\n\n3. **Create environment configuration**\n   ```bash\n   cp .env.example .env\n   ```\n   \n4. **Configure environment variables in `.env`**\n   ```bash\n   # Database Configuration\n   DB_HOST=localhost\n   DB_PORT=5432\n   DB_NAME=postgres\n   DB_USER=postgres\n   DB_PASSWORD=postgres\n   \n   # Redis Configuration\n   REDIS_HOST=localhost\n   REDIS_PORT=6379\n   \n   # Email Service\n   RESEND_API_KEY=your_resend_api_key_here\n   EMAIL_FROM=noreply@yourdomain.com\n   \n   # JWT Configuration\n   JWT_SECRET=your_jwt_secret_here\n   ```\n\n5. **Install Air for hot reload (optional but recommended)**\n   ```bash\n   go install github.com/air-verse/air@latest\n   ```\n\n## 🚀 Quick Start\n\n### Using Make (Recommended)\n\n1. **Start the application**\n   ```bash\n   make start\n   ```\n   This command will:\n   - Start PostgreSQL and Redis using Docker Compose\n   - Load environment variables from `.env`\n   - Run the Go application with hot reload using Air\n\n2. **Stop the application**\n   ```bash\n   make stop\n   ```\n\n### Manual Setup\n\n1. **Start services**\n   ```bash\n   docker compose up -d\n   ```\n\n2. **Export environment variables**\n   ```bash\n   export $(cat .env | xargs)\n   ```\n\n3. **Run the application**\n   ```bash\n   go run main.go\n   ```\n\n## 🏗️ Project Structure\n\n```\n.\n├── main.go                     # Application entry point\n├── go.mod                      # Go module dependencies\n├── docker-compose.yml          # Docker services configuration\n├── Makefile                    # Build and development commands\n├── .env.example                # Environment variables template\n├── static/                     # Frontend HTML pages\n│   ├── index.html             # Landing page\n│   ├── register.html          # User registration form\n│   ├── login.html             # User login form\n│   ├── dashboard.html         # User dashboard (protected)\n│   ├── forgot-password.html   # Forgot password form\n│   └── reset-password.html    # Password reset form\n├── internal/                   # Private application code\n│   ├── app/\n│   │   └── app.go             # Application setup and configuration\n│   ├── api/\n│   │   └── auth_handler.go    # Authentication HTTP handlers\n│   ├── middleware/\n│   │   └── auth_middleware.go # JWT authentication middleware\n│   ├── routes/\n│   │   └── routes.go          # HTTP route definitions\n│   ├── store/\n│   │   ├── database.go        # Database connection\n│   │   ├── auth_store.go      # User data operations\n│   │   ├── cache_store.go     # Redis operations\n│   │   └── email_store.go     # Email service implementation\n│   └── utils/\n│       ├── auth/\n│       │   └── auth.go        # JWT and password utilities\n│       ├── json/\n│       │   └── json.go        # JSON response utilities\n│       └── logger/\n│           └── logger.go      # Structured logging\n└── migrations/                 # Database schema migrations\n    ├── fs.go                  # Embedded filesystem for migrations\n    └── 00001_users.sql        # User table creation\n```\n\n## 📁 API Endpoints\n\n### Public Endpoints\n\n| Method | Endpoint             | Description                    |\n|--------|---------------------|--------------------------------|\n| GET    | `/health`           | Health check                   |\n| POST   | `/auth/register`    | User registration              |\n| POST   | `/auth/login`       | User login                     |\n| POST   | `/auth/forgot-password` | Request password reset     |\n| POST   | `/auth/reset-password`  | Reset password with code   |\n\n### Protected Endpoints\n\n| Method | Endpoint         | Description              |\n|--------|-----------------|--------------------------|\n| GET    | `/auth/profile` | Get user profile         |\n\n### Frontend Pages\n\n| Route                    | Description                    |\n|--------------------------|--------------------------------|\n| `/`                      | Landing page                   |\n| `/register.html`         | User registration form         |\n| `/login.html`            | User login form                |\n| `/dashboard.html`        | User dashboard (requires auth) |\n| `/forgot-password.html`  | Forgot password form           |\n| `/reset-password.html`   | Password reset form            |\n\n## 🔧 API Usage Examples\n\n### User Registration\n```bash\ncurl -X POST http://localhost:8080/auth/register \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"username\": \"johndoe\",\n    \"email\": \"john@example.com\",\n    \"password\": \"secure123\",\n    \"bio\": \"Software developer\"\n  }'\n```\n\n**Response:**\n```json\n{\n  \"data\": {\n    \"access_token\": \"eyJhbGciOiJIUzI1NiIs...\",\n    \"refresh_token\": \"eyJhbGciOiJIUzI1NiIs...\",\n    \"token_type\": \"Bearer\",\n    \"expires_in\": 86400,\n    \"user\": {\n      \"id\": 1,\n      \"username\": \"johndoe\",\n      \"email\": \"john@example.com\",\n      \"bio\": \"Software developer\",\n      \"created_at\": \"2025-09-27T10:00:00Z\",\n      \"updated_at\": \"2025-09-27T10:00:00Z\"\n    }\n  }\n}\n```\n\n### User Login\n```bash\ncurl -X POST http://localhost:8080/auth/login \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"username\": \"johndoe\",\n    \"password\": \"secure123\"\n  }'\n```\n\n### Forgot Password\n```bash\ncurl -X POST http://localhost:8080/auth/forgot-password \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"email\": \"john@example.com\"\n  }'\n```\n\n**Response:**\n```json\n{\n  \"message\": \"Reset code sent to your email\"\n}\n```\n\n### Reset Password\n```bash\ncurl -X POST http://localhost:8080/auth/reset-password \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"email\": \"john@example.com\",\n    \"code\": \"123456\",\n    \"new_password\": \"newsecure123\"\n  }'\n```\n\n### Get User Profile (Protected)\n```bash\ncurl -X GET http://localhost:8080/auth/profile \\\n  -H \"Authorization: Bearer eyJhbGciOiJIUzI1NiIs...\"\n```\n\n## 🗄️ Database Schema\n\n### Users Table\n```sql\nCREATE TABLE users (\n    id BIGSERIAL PRIMARY KEY,\n    username VARCHAR(255) NOT NULL UNIQUE,\n    email VARCHAR(255) NOT NULL UNIQUE,\n    password_hash VARCHAR(255) NOT NULL,\n    bio TEXT,\n    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,\n    updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP\n);\n\nCREATE INDEX idx_users_username ON users(username);\nCREATE INDEX idx_users_email ON users(email);\n```\n\n## 🐳 Docker Services\n\nThe `docker-compose.yml` sets up:\n\n1. **PostgreSQL Database**\n   - Container: `postgres-project`\n   - Port: `5432`\n   - Persistent data storage\n   - Health checks enabled\n\n2. **Redis Cache**\n   - Container: `redis-project`\n   - Port: `6379`\n   - Used for reset code storage\n   - 15-minute code expiration\n\n3. **Adminer** (Database Admin UI)\n   - Container: `adminer`\n   - Port: `9090`\n   - Access: http://localhost:9090\n\n## 🔒 Security Features\n\n### Password Security\n- **bcrypt Hashing**: All passwords are hashed using bcrypt with salt\n- **Minimum Length**: 6 characters minimum (configurable)\n- **No Plain Text**: Passwords are never stored in plain text\n\n### JWT Authentication\n- **Access Tokens**: Short-lived tokens (24 hours)\n- **Refresh Tokens**: Long-lived tokens for token renewal\n- **Secure Headers**: Proper JWT header validation\n- **Claims Validation**: User ID and email verification\n\n### Reset Code Security\n- **6-Digit Codes**: Cryptographically secure random generation\n- **Time Expiration**: 15-minute automatic expiration\n- **Single Use**: Codes are deleted after successful use\n- **Email Verification**: Codes sent only to registered emails\n\n## 📧 Email Templates\n\nThe system includes professional HTML email templates for:\n\n### Password Reset Email\n- Clean, responsive design\n- Large, readable reset code\n- Clear expiration notice\n- Security warning for unauthorized requests\n\n## 🎨 Frontend Features\n\n### Responsive Design\n- Mobile-first responsive design\n- Modern CSS with CSS Grid and Flexbox\n- Professional color scheme and typography\n- Loading states and animations\n\n### User Experience\n- **Form Validation**: Client-side and server-side validation\n- **Loading Indicators**: Visual feedback during requests\n- **Error Handling**: Clear error messages and recovery options\n- **Success States**: Confirmation messages and redirects\n- **Auto-Fill**: Email persistence during password reset flow\n\n### Pages Features\n- **Landing Page**: Clean introduction with navigation\n- **Registration**: Complete signup with bio field\n- **Login**: Secure authentication with forgot password link\n- **Dashboard**: Protected user profile display\n- **Forgot Password**: Email submission with validation\n- **Reset Password**: Code entry with password confirmation\n\n## 🧪 Testing the Application\n\n### Backend Health Check\n```bash\ncurl http://localhost:8080/health\n```\n\n### Frontend Access\n- **Main Application**: http://localhost:8080\n- **Database Admin**: http://localhost:9090\n- **Registration**: http://localhost:8080/register.html\n- **Login**: http://localhost:8080/login.html\n\n### Complete Authentication Flow Test\n1. Register a new user via frontend or API\n2. Log in to receive JWT tokens\n3. Access protected profile endpoint\n4. Test forgot password flow\n5. Verify email reset code functionality\n6. Complete password reset process\n\n\u003c!-- \n## 🚀 Production Deployment\n\n### Environment Setup\n1. **Secure JWT Secret**: Use a cryptographically secure random string\n2. **Database Credentials**: Use strong, unique credentials\n3. **SSL/TLS**: Enable HTTPS for all endpoints\n4. **Environment Variables**: Never commit secrets to version control\n\n### Performance Optimizations\n1. **Connection Pooling**: Configure appropriate database pool sizes\n2. **Redis Persistence**: Configure Redis persistence for production\n3. **Logging**: Set appropriate log levels\n4. **Rate Limiting**: Implement API rate limiting\n5. **CORS**: Configure CORS for your domain\n\n### Monitoring\n- Health check endpoint for load balancers\n- Structured logging for monitoring tools\n- Database connection monitoring\n- Redis connection monitoring\n- Email service monitoring --\u003e\n\n## 🤝 Contributing\n\n1. Fork the repository\n2. Create a feature branch (`git checkout -b feature/amazing-feature`)\n3. Commit your changes (`git commit -m 'Add some amazing feature'`)\n4. Push to the branch (`git push origin feature/amazing-feature`)\n5. Open a Pull Request\n\n### Development Guidelines\n- Follow Go best practices and conventions\n- Add tests for new features\n- Update documentation for API changes\n- Ensure security best practices\n- Test email functionality with real SMTP service\n\n## 📝 License\n\nThis project is open source and available under the [MIT License](LICENSE).\n\n## 🆘 Troubleshooting\n\n### Common Issues\n\n1. **Database connection failed**\n   - Ensure Docker is running: `docker compose ps`\n   - Check database credentials in `.env`\n   - Verify PostgreSQL container health\n\n2. **Redis connection failed**\n   - Ensure Redis container is running\n   - Check Redis configuration in `.env`\n   - Verify Redis container health\n\n3. **Email not sending**\n   - Verify `RESEND_API_KEY` in `.env`\n   - Check Resend account status and credits\n   - Verify `EMAIL_FROM` domain is configured in Resend\n\n4. **JWT token issues**\n   - Ensure `JWT_SECRET` is set in `.env`\n   - Check token expiration settings\n   - Verify Authorization header format: `Bearer \u003ctoken\u003e`\n\n5. **Frontend not loading**\n   - Check if static files are being served correctly\n   - Verify port configuration\n   - Check browser console for JavaScript errors\n\n6. **Password reset code not working**\n   - Check Redis connection and data persistence\n   - Verify code hasn't expired (15 minutes)\n   - Ensure email matches exactly\n\n### Logging and Debugging\n- Application logs show detailed error information\n- Use `make logs` to view Docker container logs\n- Enable debug logging by setting log level in environment\n\n### Getting Help\n\nIf you encounter any issues:\n1. Check the application logs for detailed error messages\n2. Verify all environment variables are properly set\n3. Ensure all Docker containers are running and healthy\n4. Test individual components (database, Redis, email service)\n5. Review the API documentation and test with curl commands\n\n----------","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdeepraj02%2Fbackend-starter-golang","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdeepraj02%2Fbackend-starter-golang","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdeepraj02%2Fbackend-starter-golang/lists"}