A high-performance REST API built with Go and Gin framework, featuring Firebase integration, JWT authentication, and AI service connectivity.
- High Performance: Built with Go and Gin framework
- Authentication: Firebase Authentication integration
- Database: Firebase Firestore for data persistence
- File Storage: Firebase Storage for file uploads
- AI Integration: OpenRouter and Replicate API integration
- CORS Support: Configurable cross-origin resource sharing
- Middleware: Request logging, authentication, and error handling
- Docker Support: Containerized deployment ready
- Environment Configuration: Flexible environment-based configuration
- Language: Go 1.23+
- Framework: Gin Web Framework
- Database: Firebase Firestore
- Authentication: Firebase Auth
- Storage: Firebase Storage
- AI Services: OpenRouter API, Replicate API
- Containerization: Docker
- Go 1.23 or later
- Firebase project with Firestore, Authentication, and Storage enabled
- OpenRouter API key (optional, for AI features)
- Replicate API key (optional, for AI features)
-
Clone the repository
git clone <repository-url> cd backend
-
Install dependencies
go mod download
-
Set up environment variables
cp .env.example .env
Fill in your configuration in
.env
:PORT=8080 FIREBASE_PROJECT_ID=your_project_id FIREBASE_STORAGE_BUCKET=your_project.firebasestorage.app GOOGLE_APPLICATION_CREDENTIALS=serviceAccountKey.json OPENROUTER_API_KEY=your_openrouter_api_key REPLICATE_API_KEY=your_replicate_api_key
-
Set up Firebase Service Account
- Go to Firebase Console β Project Settings β Service Accounts
- Generate a new private key
- Save the JSON file as
serviceAccountKey.json
in the backend directory - Never commit this file to version control
-
Run the development server
go run main.go
-
Test the API Navigate to http://localhost:8080
backend/
βββ cmd/ # Application entry points
βββ controllers/ # Request handlers
β βββ auth.go # Authentication controllers
β βββ chat.go # Chat-related controllers
β βββ user.go # User management controllers
βββ firebase/ # Firebase configuration and clients
β βββ firebase.go # Firebase initialization
β βββ storage.go # Firebase Storage utilities
βββ middleware/ # HTTP middleware
β βββ auth.go # Authentication middleware
β βββ cors.go # CORS middleware
βββ models/ # Data models and schemas
β βββ user.go # User model
β βββ chat.go # Chat model
β βββ message.go # Message model
βββ routes/ # Route definitions
β βββ routes.go # Main route setup
βββ services/ # Business logic services
β βββ ai.go # AI service integrations
β βββ chat.go # Chat service
β βββ user.go # User service
βββ temp/ # Temporary file storage
βββ main.go # Application entry point
βββ go.mod # Go module definition
βββ go.sum # Go module checksums
βββ Dockerfile # Docker configuration
βββ .dockerignore # Docker ignore file
go run main.go
- Start development servergo build
- Build the applicationgo test ./...
- Run all testsgo mod tidy
- Clean up dependenciesdocker build -t backend .
- Build Docker imagedocker run -p 8080:8080 backend
- Run Docker container
Create a .env
file in the root directory with the following variables:
# Server Configuration
PORT=8080
# Firebase Configuration
FIREBASE_PROJECT_ID=your_project_id
FIREBASE_STORAGE_BUCKET=your_project.firebasestorage.app
GOOGLE_APPLICATION_CREDENTIALS=serviceAccountKey.json
# AI Service APIs (Optional)
OPENROUTER_API_KEY=your_openrouter_api_key
REPLICATE_API_KEY=your_replicate_api_key
# Environment
GO_ENV=development
-
Create a Firebase Project
- Go to Firebase Console
- Create a new project or use existing one
-
Enable Required Services
- Authentication (Email/Password)
- Firestore Database
- Storage
-
Generate Service Account Key
- Project Settings β Service Accounts
- Generate new private key
- Download JSON file as
serviceAccountKey.json
-
Security Rules Update Firestore and Storage security rules as needed for your use case.
POST /api/auth/register
- Register new userPOST /api/auth/login
- User loginPOST /api/auth/logout
- User logoutGET /api/auth/verify
- Verify JWT token
GET /api/users/profile
- Get user profilePUT /api/users/profile
- Update user profilePOST /api/users/avatar
- Upload user avatar
GET /api/chat/conversations
- Get user conversationsPOST /api/chat/conversations
- Create new conversationGET /api/chat/conversations/:id/messages
- Get conversation messagesPOST /api/chat/conversations/:id/messages
- Send new message
POST /api/ai/chat
- Chat with AIPOST /api/ai/generate
- Generate content with AI
The API uses Firebase Authentication with JWT tokens:
-
Client Authentication
- Frontend sends Firebase ID token in Authorization header
- Backend verifies token with Firebase Admin SDK
-
Protected Routes
- Use
AuthMiddleware
to protect routes - Middleware validates Firebase tokens
- User information available in request context
- Use
-
Example Usage
curl -H "Authorization: Bearer YOUR_FIREBASE_ID_TOKEN" \ http://localhost:8080/api/users/profile
-
Build the image
docker build -t your-app-backend .
-
Run the container
docker run -p 8080:8080 \ -e FIREBASE_PROJECT_ID=your_project_id \ -e FIREBASE_STORAGE_BUCKET=your_bucket \ -v /path/to/serviceAccountKey.json:/app/serviceAccountKey.json \ your-app-backend
- Set environment variables on your hosting platform
- Upload
serviceAccountKey.json
securely (not in repository) - Configure firewall rules for port 8080
- Set up reverse proxy (nginx) if needed
- Google Cloud Run (Recommended for Firebase integration)
- AWS ECS/Lambda
- DigitalOcean App Platform
- Railway
- Heroku
Run tests with:
go test ./...
Run tests with coverage:
go test -cover ./...
Run specific package tests:
go test ./controllers
The API includes:
- Request/response logging via Gin middleware
- Error handling and logging
- Performance metrics (add monitoring tools as needed)
For production, consider adding:
- Prometheus metrics
- Distributed tracing
- Health check endpoints
Update CORS settings in main.go
:
router.Use(cors.New(cors.Config{
AllowOrigins: []string{"https://yourdomain.com"},
AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowHeaders: []string{"Origin", "Content-Type", "Accept", "Authorization"},
AllowCredentials: true,
}))
Consider adding rate limiting middleware for production use.
- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature
- Commit your changes:
git commit -m 'Add amazing feature'
- Push to the branch:
git push origin feature/amazing-feature
- Open a Pull Request
- Follow Go best practices and conventions
- Use
gofmt
for code formatting - Add comments for exported functions
- Write tests for new features
This project is licensed under the MIT License - see the LICENSE file for details.
If you encounter any issues or have questions:
- Check the Issues section
- Create a new issue with detailed information
- Include logs and steps to reproduce the problem
- Gin Web Framework for the excellent HTTP framework
- Firebase for backend services
- Go team for the amazing language
- Open source community for various packages used in this project