Skip to content

A full-stack social media platform built with Go backend and React frontend, featuring user authentication, posts, comments, followers, and real-time interactions.

Notifications You must be signed in to change notification settings

karthikbhandary2/Social

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

48 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Social Media Platform

A full-stack social media platform built with Go backend and React frontend, featuring user authentication, posts, comments, followers, and real-time interactions.

πŸš€ Features

  • User Management: Registration, authentication, and profile management
  • Posts & Comments: Create, read, update, and delete posts with commenting system
  • Social Features: Follow/unfollow users, personalized feed
  • Authentication: JWT-based authentication with secure token management
  • Rate Limiting: Built-in rate limiting for API protection
  • Caching: Redis integration for improved performance
  • Email Integration: SendGrid integration for notifications
  • API Documentation: Swagger/OpenAPI documentation
  • Database Migrations: Structured database schema management
  • Testing: Comprehensive test suite

πŸ›  Tech Stack

Backend

  • Language: Go 1.23.4
  • Framework: Chi Router
  • Database: PostgreSQL
  • Cache: Redis
  • Authentication: JWT tokens
  • Email: SendGrid
  • Documentation: Swagger/Swaggo
  • Logging: Zap logger

Frontend

  • Framework: React 19.0.0
  • Build Tool: Vite
  • Routing: React Router DOM
  • Language: JavaScript/TypeScript

DevOps & Tools

  • Containerization: Docker & Docker Compose
  • Hot Reload: Air (Go) & Vite (React)
  • CI/CD: GitHub Actions
  • Database Migrations: golang-migrate
  • Testing: Go testing framework

πŸ“ Project Structure

Social/
β”œβ”€β”€ cmd/                          # Application entry points
β”‚   β”œβ”€β”€ api/                      # REST API server
β”‚   β”‚   β”œβ”€β”€ main.go              # Main application entry
β”‚   β”‚   β”œβ”€β”€ api.go               # API configuration and routes
β”‚   β”‚   β”œβ”€β”€ auth.go              # Authentication handlers
β”‚   β”‚   β”œβ”€β”€ users.go             # User management endpoints
β”‚   β”‚   β”œβ”€β”€ posts.go             # Post management endpoints
β”‚   β”‚   β”œβ”€β”€ feed.go              # Feed generation endpoints
β”‚   β”‚   β”œβ”€β”€ middleware.go        # HTTP middleware
β”‚   β”‚   β”œβ”€β”€ errors.go            # Error handling
β”‚   β”‚   β”œβ”€β”€ json.go              # JSON utilities
β”‚   β”‚   β”œβ”€β”€ health.go            # Health check endpoint
β”‚   β”‚   └── *_test.go            # API tests
β”‚   └── migrate/                 # Database migration tools
β”‚       β”œβ”€β”€ migrations/          # SQL migration files
β”‚       └── seed/               # Database seeding
β”œβ”€β”€ internal/                    # Private application code
β”‚   β”œβ”€β”€ auth/                   # Authentication logic
β”‚   β”‚   β”œβ”€β”€ auth.go             # Auth interfaces
β”‚   β”‚   β”œβ”€β”€ jwt.go              # JWT implementation
β”‚   β”‚   └── mocks.go            # Auth mocks for testing
β”‚   β”œβ”€β”€ db/                     # Database connection and utilities
β”‚   β”‚   β”œβ”€β”€ db.go               # Database connection setup
β”‚   β”‚   └── seed.go             # Database seeding logic
β”‚   β”œβ”€β”€ env/                    # Environment configuration
β”‚   β”‚   └── env.go              # Environment variable helpers
β”‚   β”œβ”€β”€ mailer/                 # Email service
β”‚   β”‚   β”œβ”€β”€ mailer.go           # Mailer interface
β”‚   β”‚   β”œβ”€β”€ sendgrid.go         # SendGrid implementation
β”‚   β”‚   └── templates/          # Email templates
β”‚   β”œβ”€β”€ ratelimiter/            # Rate limiting
β”‚   β”‚   β”œβ”€β”€ ratelimiter.go      # Rate limiter interface
β”‚   β”‚   └── fixed-window.go     # Fixed window implementation
β”‚   └── store/                  # Data access layer
β”‚       β”œβ”€β”€ storage.go          # Storage interfaces
β”‚       β”œβ”€β”€ users.go            # User data operations
β”‚       β”œβ”€β”€ posts.go            # Post data operations
β”‚       β”œβ”€β”€ comments.go         # Comment data operations
β”‚       β”œβ”€β”€ followers.go        # Follower relationships
β”‚       β”œβ”€β”€ role.go             # User roles
β”‚       β”œβ”€β”€ pagination.go       # Pagination utilities
β”‚       β”œβ”€β”€ mocks.go            # Store mocks for testing
β”‚       └── cache/              # Caching layer
β”œβ”€β”€ web/                        # Frontend React application
β”‚   β”œβ”€β”€ src/                    # React source code
β”‚   β”‚   β”œβ”€β”€ App.jsx             # Main App component
β”‚   β”‚   β”œβ”€β”€ main.jsx            # React entry point
β”‚   β”‚   β”œβ”€β”€ ConfirmationPage.tsx # Email confirmation page
β”‚   β”‚   β”œβ”€β”€ App.css             # App styles
β”‚   β”‚   β”œβ”€β”€ index.css           # Global styles
β”‚   β”‚   └── assets/             # Static assets
β”‚   β”œβ”€β”€ public/                 # Public assets
β”‚   β”œβ”€β”€ package.json            # Node.js dependencies
β”‚   β”œβ”€β”€ vite.config.js          # Vite configuration
β”‚   β”œβ”€β”€ eslint.config.js        # ESLint configuration
β”‚   └── index.html              # HTML template
β”œβ”€β”€ docs/                       # API documentation
β”‚   β”œβ”€β”€ docs.go                 # Generated Swagger docs
β”‚   β”œβ”€β”€ swagger.json            # Swagger JSON spec
β”‚   └── swagger.yaml            # Swagger YAML spec
β”œβ”€β”€ scripts/                    # Utility scripts
β”‚   β”œβ”€β”€ db_init.sql             # Database initialization
β”‚   └── test_concurrency.go     # Concurrency testing
β”œβ”€β”€ bin/                        # Compiled binaries
β”œβ”€β”€ .github/                    # GitHub workflows
β”‚   └── workflows/              # CI/CD pipelines
β”œβ”€β”€ go.mod                      # Go module definition
β”œβ”€β”€ go.sum                      # Go module checksums
β”œβ”€β”€ makefile                    # Build automation
β”œβ”€β”€ docker-compose.yml          # Docker services
β”œβ”€β”€ .air.toml                   # Air hot reload config
β”œβ”€β”€ .envrc                      # Environment variables
β”œβ”€β”€ .gitignore                  # Git ignore rules
└── README.md                   # This file

🚦 Prerequisites

  • Go: 1.23.4 or later
  • Node.js: 18.0 or later
  • PostgreSQL: 12.0 or later
  • Redis: 6.0 or later (optional, for caching)
  • Docker & Docker Compose: For containerized setup

⚑ Quick Start

1. Clone the Repository

git clone https://github.com/karthikbhandary2/Social.git
cd Social

2. Environment Setup

Create a .envrc file in the root directory:

# Database Configuration
export DB_ADDR="postgres://username:password@localhost/social?sslmode=disable"
export DB_MAX_OPEN_CONNS=30
export DB_MAX_IDLE_CONNS=30
export DB_MAX_IDLE_TIME="15m"

# Server Configuration
export ADDR=":8082"
export EXTERNAL_URL="localhost:8082"
export FRONTEND_URL="http://localhost:5173"
export ENV="development"

# Redis Configuration (optional)
export REDIS_ADDR="localhost:6379"
export REDIS_PW=""
export REDIS_DB=0
export REDIS_ENABLED=true

# Authentication
export AUTH_BASIC_USER="admin"
export AUTH_BASIC_PASS="admin"
export AUTH_TOKEN_SECRET="your-secret-key"

# Email Configuration (SendGrid)
export FROM_EMAIL="[email protected]"
export SENDGRID_API_KEY="your-sendgrid-api-key"

# Rate Limiting
export RATELIMITER_REQUESTS_COUNT=20
export RATE_LIMITER_ENABLED=true

3. Database Setup

Option A: Using Docker (Recommended)

# Start PostgreSQL with Docker Compose
docker-compose up -d db

# Wait for database to be ready, then run migrations
make migrate-up

# Seed the database with sample data
make seed

Option B: Local PostgreSQL

# Create database
createdb social

# Run migrations
make migrate-up

# Seed database
make seed

4. Install Dependencies

Backend Dependencies

go mod tidy

Frontend Dependencies

cd web
npm install
cd ..

5. Start the Application

Development Mode (with hot reload)

Terminal 1 - Backend:

# Install Air for hot reload (if not already installed)
go install github.com/cosmtrek/air@latest

# Start backend with hot reload
air

Terminal 2 - Frontend:

cd web
npm run dev

Production Mode

Backend:

go build -o bin/main cmd/api/*.go
./bin/main

Frontend:

cd web
npm run build
npm run preview

6. Access the Application

πŸ”§ Development

Available Make Commands

# Database Operations
make migrate-up              # Run all pending migrations
make migrate-down           # Rollback last migration
make migrate-force ARG=1    # Force migration to specific version
make seed                   # Seed database with sample data

# Documentation
make gen-docs              # Generate Swagger documentation

# Testing
make test                  # Run all tests

# Create new migration
make migration create_users_table

API Endpoints

Authentication

  • POST /v1/authentication/user - User login
  • POST /v1/users - User registration
  • PUT /v1/users/activate/:token - Account activation

Users

  • GET /v1/users/:id - Get user profile
  • PUT /v1/users/:id/follow - Follow user
  • PUT /v1/users/:id/unfollow - Unfollow user

Posts

  • GET /v1/posts - List posts with pagination
  • POST /v1/posts - Create new post
  • GET /v1/posts/:id - Get specific post
  • PATCH /v1/posts/:id - Update post
  • DELETE /v1/posts/:id - Delete post

Comments

  • GET /v1/posts/:id/comments - Get post comments
  • POST /v1/posts/:id/comments - Add comment

Feed

  • GET /v1/users/:id/feed - Get user's personalized feed

Testing

# Run all tests
go test ./...

# Run tests with coverage
go test -cover ./...

# Run specific test
go test ./cmd/api -v

# Run tests with race detection
go test -race ./...

Database Migrations

Create a new migration:

make migration create_new_table

This creates two files in cmd/migrate/migrations/:

  • 000X_create_new_table.up.sql - Forward migration
  • 000X_create_new_table.down.sql - Rollback migration

🐳 Docker Deployment

Full Stack with Docker Compose

# Build and start all services
docker-compose up --build

# Start in background
docker-compose up -d

# View logs
docker-compose logs -f

# Stop services
docker-compose down

Individual Service Containers

# Build backend image
docker build -t social-api .

# Build frontend image
cd web && docker build -t social-web .

πŸ§ͺ Testing

The project includes comprehensive tests:

  • Unit Tests: Individual component testing
  • Integration Tests: API endpoint testing
  • Concurrency Tests: Race condition testing

Test Structure

cmd/api/
β”œβ”€β”€ api_test.go          # API integration tests
β”œβ”€β”€ user_test.go         # User endpoint tests
└── test_utils.go        # Testing utilities

πŸ“Š Monitoring & Metrics

The application exposes metrics at /debug/vars:

  • Version: Application version
  • Database: Connection pool stats
  • Goroutines: Active goroutine count
  • Memory: Runtime memory statistics

πŸ”’ Security Features

  • JWT Authentication: Secure token-based authentication
  • Rate Limiting: Configurable request rate limiting
  • CORS: Cross-origin resource sharing configuration
  • Input Validation: Request payload validation
  • SQL Injection Protection: Parameterized queries
  • Password Hashing: Bcrypt password hashing

πŸš€ Deployment

Environment Variables for Production

export ENV="production"
export DB_ADDR="postgres://user:pass@prod-db:5432/social?sslmode=require"
export REDIS_ADDR="prod-redis:6379"
export EXTERNAL_URL="https://your-domain.com"
export FRONTEND_URL="https://your-frontend-domain.com"

Health Checks

The application provides health check endpoints:

  • GET /v1/health - Basic health status
  • GET /debug/vars - Detailed metrics

πŸ“ License

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

πŸ†˜ Troubleshooting

Common Issues

  1. Database Connection Failed

    # Check if PostgreSQL is running
    pg_isready -h localhost -p 5432
    
    # Verify connection string in .envrc
  2. Redis Connection Failed

    # Check if Redis is running
    redis-cli ping
    
    # Disable Redis if not needed
    export REDIS_ENABLED=false
  3. Migration Errors

    # Check migration status
    migrate -path ./cmd/migrate/migrations/ -database $DB_ADDR version
    
    # Force to specific version if needed
    make migrate-force ARG=1
  4. Port Already in Use

    # Change port in .envrc
    export ADDR=":8083"

πŸ“ž Support

For support and questions:

  • Create an issue on GitHub
  • Check existing documentation
  • Review the API documentation at /swagger/index.html

Happy Coding! πŸŽ‰

About

A full-stack social media platform built with Go backend and React frontend, featuring user authentication, posts, comments, followers, and real-time interactions.

Resources

Stars

Watchers

Forks

Packages

No packages published