Skip to content

Chimera-Platform/chimera-backend

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

1 Commit
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Backend - Go REST API

A high-performance REST API built with Go and Gin framework, featuring Firebase integration, JWT authentication, and AI service connectivity.

πŸš€ Features

  • 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

πŸ› οΈ Tech Stack

πŸ“‹ Prerequisites

  • 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)

⚑ Quick Start

  1. Clone the repository

    git clone <repository-url>
    cd backend
  2. Install dependencies

    go mod download
  3. 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
  4. 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
  5. Run the development server

    go run main.go
  6. Test the API Navigate to http://localhost:8080

πŸ“ Project Structure

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

πŸ”§ Available Commands

  • go run main.go - Start development server
  • go build - Build the application
  • go test ./... - Run all tests
  • go mod tidy - Clean up dependencies
  • docker build -t backend . - Build Docker image
  • docker run -p 8080:8080 backend - Run Docker container

πŸ” Environment Variables

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

πŸ”‘ Firebase Setup

  1. Create a Firebase Project

  2. Enable Required Services

    • Authentication (Email/Password)
    • Firestore Database
    • Storage
  3. Generate Service Account Key

    • Project Settings β†’ Service Accounts
    • Generate new private key
    • Download JSON file as serviceAccountKey.json
  4. Security Rules Update Firestore and Storage security rules as needed for your use case.

πŸ”— API Endpoints

Authentication

  • POST /api/auth/register - Register new user
  • POST /api/auth/login - User login
  • POST /api/auth/logout - User logout
  • GET /api/auth/verify - Verify JWT token

Users

  • GET /api/users/profile - Get user profile
  • PUT /api/users/profile - Update user profile
  • POST /api/users/avatar - Upload user avatar

Chat

  • GET /api/chat/conversations - Get user conversations
  • POST /api/chat/conversations - Create new conversation
  • GET /api/chat/conversations/:id/messages - Get conversation messages
  • POST /api/chat/conversations/:id/messages - Send new message

AI Services

  • POST /api/ai/chat - Chat with AI
  • POST /api/ai/generate - Generate content with AI

πŸ”’ Authentication

The API uses Firebase Authentication with JWT tokens:

  1. Client Authentication

    • Frontend sends Firebase ID token in Authorization header
    • Backend verifies token with Firebase Admin SDK
  2. Protected Routes

    • Use AuthMiddleware to protect routes
    • Middleware validates Firebase tokens
    • User information available in request context
  3. Example Usage

    curl -H "Authorization: Bearer YOUR_FIREBASE_ID_TOKEN" \
         http://localhost:8080/api/users/profile

🐳 Docker Deployment

  1. Build the image

    docker build -t your-app-backend .
  2. 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

πŸš€ Production Deployment

Environment Setup

  1. Set environment variables on your hosting platform
  2. Upload serviceAccountKey.json securely (not in repository)
  3. Configure firewall rules for port 8080
  4. Set up reverse proxy (nginx) if needed

Recommended Platforms

  • Google Cloud Run (Recommended for Firebase integration)
  • AWS ECS/Lambda
  • DigitalOcean App Platform
  • Railway
  • Heroku

πŸ§ͺ Testing

Run tests with:

go test ./...

Run tests with coverage:

go test -cover ./...

Run specific package tests:

go test ./controllers

πŸ“Š Monitoring & Logging

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

πŸ”§ Configuration

CORS Configuration

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,
}))

Rate Limiting

Consider adding rate limiting middleware for production use.

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/amazing-feature
  3. Commit your changes: git commit -m 'Add amazing feature'
  4. Push to the branch: git push origin feature/amazing-feature
  5. Open a Pull Request

Code Style

  • Follow Go best practices and conventions
  • Use gofmt for code formatting
  • Add comments for exported functions
  • Write tests for new features

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ†˜ Support

If you encounter any issues or have questions:

  1. Check the Issues section
  2. Create a new issue with detailed information
  3. Include logs and steps to reproduce the problem

πŸ™ Acknowledgments

  • 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

About

Backend service for Chimera Platform

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published