A RESTful API for a social media platform built with Go, featuring user authentication, posts, comments, and social interactions.
-
User Management
- User registration with email verification
- JWT-based authentication
- User activation via token
- User profiles and feeds
-
Social Interactions
- Create, read, update, and delete posts
- Comment on posts
- Follow/unfollow users
- Personalized user feed
-
Security
- JWT token authentication
- Basic auth for admin endpoints
- Role-based access control (admin, moderator)
- Password hashing
- Rate limiting capabilities
-
Monitoring & Health
- Health check endpoint
- Debug metrics via expvar
- Comprehensive logging
- Language: Go
- Router: Chi
- Database: PostgreSQL (assumed from structure)
- Authentication: JWT tokens
- Email: Amazon SES
- Cache: Redis
Social/
├── .github/ # GitHub workflows and CI/CD
├── bin/ # Compiled binaries
├── cmd/ # Application entrypoints
│ ├── api/ # Main API server
│ └── migrate/ # Database migrations
├── docs/ # API documentation
├── internal/ # Private application code
│ ├── auth/ # Authentication logic
│ ├── db/ # Database layer
│ ├── env/ # Environment configuration
│ ├── mailer/ # Email service
│ ├── ratelimiter/ # Rate limiting
│ └── store/ # Data access layer
├── scripts/ # Build and deployment scripts
├── web/ # Web assets (if any)
├── .env.sample # Environment variables template
├── docker-compose.yml # Docker setup
├── go.mod # Go dependencies
├── go.sum # Dependency checksums
└── Makefile # Build automation
GET /v1/health # Health check (public)
GET /v1/debug/vars # Runtime metrics (basic auth required)
POST /v1/auth/register # Register new user
POST /v1/auth/token # Generate JWT token
PUT /v1/users/activate/{token} # Activate user account
GET /v1/users/{userID} # Get user profile (auth required)
POST /v1/users/{userID}/follow # Follow user (auth required)
POST /v1/users/{userID}/unfollow # Unfollow user (auth required)
GET /v1/users/feed # Get user feed (auth required)
POST /v1/posts/create # Create post (auth required)
GET /v1/posts/{postID} # Get post by ID (auth required)
PATCH /v1/posts/{postID} # Update post (moderator+ required)
DELETE /v1/posts/{postID} # Delete post (admin required)
POST /v1/posts/{postID}/comments # Create comment (auth required)
- Go 1.24 or higher
- PostgreSQL 14 or higher
- Docker
- Make
- Clone the repository:
git clone https://github.com/anmol420/social.git
cd social- Copy environment variables:
cp .env.sample .env- Configure your
.envfile with appropriate values:
ADDR=""
EXTERNAL_URL=""
DATABASE_ADDR=""
MAX_OPEN_CONNS=""
MAX_IDLE_CONNS=""
MAX_IDLE_TIME=""
MAILER_FROM_EMAIL=""
MAILER_REGION=""
FRONTEND_URL=""
AUTH_BASIC_USERNAME=""
AUTH_BASIC_PASSWORD=""
AUTH_JWT_TOKEN_SECRET=""
REDIS_ADDR=""
REDIS_DB=""
REDIS_ENABLED=""
RATELIMITER_REQUESTS_COUNT=""
RATELIMITER_ENABLED=""- Install dependencies:
go mod download- Run database migrations:
make migrate-up- Start the server:
air
# or
go run cmd/api/main.goThe API will be available at http://localhost:8080 (or your configured port).
- Build and start services:
docker-compose up -d- Run migrations:
docker-compose exec api make migrate-up- View logs:
docker-compose logs -f api- Stop services:
docker-compose downcurl -X POST http://localhost:8080/v1/auth/register \
-H "Content-Type: application/json" \
-d '{
"username": "johndoe",
"email": "john@example.com",
"password": "securepassword123"
}'curl -X POST http://localhost:8080/v1/auth/token \
-H "Content-Type: application/json" \
-d '{
"email": "john@example.com",
"password": "securepassword123"
}'Include the JWT token in the Authorization header:
curl -X GET http://localhost:8080/v1/users/feed \
-H "Authorization: Bearer YOUR_JWT_TOKEN"The API implements role-based access control with the following roles:
- User: Basic access to create posts, comments, follow users
- Moderator: Can update any post
- Admin: Full access including post deletion
Rate limiting is implemented to prevent abuse. Default limits:
- 200 requests per minute per IP
- Configurable per endpoint
The API returns consistent error responses:
{
"error": {
"code": "ERROR_CODE",
"message": "Human readable error message",
"details": {}
}
}Common HTTP status codes:
200- Success201- Created400- Bad Request401- Unauthorized403- Forbidden404- Not Found500- Internal Server Error
make migrate-create <migration_name># Apply all pending migrations
make migrate-up
# Rollback last migration
make migrate-downcurl http://localhost:8080/v1/healthResponse:
{
"status": "ok",
"timestamp": "2024-02-07T10:30:00Z"
}Access runtime metrics (requires basic auth):
curl -u admin:password http://localhost:8080/v1/debug/vars- All passwords are hashed using bcrypt
- JWT tokens expire after a configured duration
- HTTPS should be enforced in production
- SQL injection prevention through parameterized queries
- Input validation on all endpoints
- CORS configured for specific origins
- Rate limiting to prevent abuse
- Secure headers configured
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
- Follow Go best practices and idioms
- Write tests for new features
- Update documentation for API changes
- Use meaningful commit messages
- Keep functions focused and small
- Add comments for complex logic
Database Connection Failed
- Verify database credentials in
.env - Ensure PostgreSQL is running
- Check network connectivity
JWT Token Invalid
- Verify
JWT_SECRETis set - Check token expiration
- Ensure proper Authorization header format
Migration Errors
- Check migration files for syntax errors
- Verify database permissions
- Review migration logs
See CHANGELOG.md for a detailed history of changes.