Skip to content

Latest commit

 

History

3 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

BMG Go Backend

A robust inventory management system built with Go, featuring RESTful APIs, authentication, file uploads, and comprehensive middleware support.

Features

  • RESTful API: Clean API design following best practices
  • Authentication & Authorization: JWT-based authentication with session management
  • File Upload: Secure file upload and storage capabilities
  • Middleware Stack: CORS, rate limiting, logging, and authentication middleware
  • Database Integration: PostgreSQL with migrations support
  • Repository Pattern: Clean architecture with separation of concerns
  • Validation: Input validation using go-playground/validator
  • Health Checks: Built-in health check endpoint for monitoring

Tech Stack

  • Go 1.25+: Modern Go with latest features
  • Chi Router: Lightweight, fast HTTP router
  • PostgreSQL: Primary database
  • sqlx: SQL toolkit with enhanced features
  • JWT: JSON Web Tokens for authentication
  • Validator: go-playground/validator for input validation
  • OAuth2: Google OAuth integration

Project Structure

.
├── cmd/
│   └── api/
│       ├── main.go              # Application entry point
│       ├── routes.go            # Route definitions
│       ├── healthcheck.go       # Health check handler
│       ├── items.go             # Item handlers
│       └── helpers.go           # Helper functions
├── internal/
│   ├── config/                  # Configuration management
│   ├── data/                    # Data models
│   ├── database/                # Database connection
│   │   └── postgres.go
│   ├── domain/                  # Domain models
│   │   ├── error.go
│   │   ├── item.go
│   │   └── user.go
│   ├── dto/                     # Data Transfer Objects
│   │   ├── auth_dto.go
│   │   ├── item_dto.go
│   │   └── user_dto.go
│   ├── handler/                 # HTTP handlers
│   │   ├── auth_handler.go
│   │   ├── item_handler.go
│   │   ├── upload_handler.go
│   │   └── user_handler.go
│   ├── middleware/              # HTTP middleware
│   │   ├── auth.go
│   │   ├── cors.go
│   │   ├── logger.go
│   │   └── rate_limit.go
│   ├── repository/              # Data access layer
│   │   ├── item_repository.go
│   │   ├── user_repository.go
│   │   └── session_repository.go
│   └── service/                 # Business logic layer
│       ├── auth_service.go
│       ├── item_service.go
│       ├── user_service.go
│       └── storage_service.go
├── pkg/
│   ├── jwt/                     # JWT utilities
│   ├── utils/                   # Utility functions
│   │   └── response.go
│   └── validator/               # Custom validators
├── migrations/                  # Database migrations
├── Makefile                     # Build automation
└── go.mod

Getting Started

Prerequisites

  • Go 1.25 or higher
  • PostgreSQL 12+
  • Make (optional, for using Makefile commands)

Installation

  1. Clone the repository:
git clone https://github.com/PaulBabatuyi/BMG-Go-Backend.git
cd BMG-Go-Backend
  1. Install dependencies:
go mod download
  1. Set up environment variables:
cp .env.example .env
# Edit .env with your configuration
  1. Set up the database:
createdb bmginventory
  1. Run migrations:
make migrate-up

Running the Application

Using Go directly:

go run cmd/api/main.go

Using Make:

make run

With custom flags:

go run cmd/api/main.go -port=8080 -env=production

The server will start on http://localhost:4000 by default.

Using Docker

# Start all services
make docker

# Stop all services
make docker-down

API Endpoints

Health Check

GET /v1/healthcheck

Response:

{
  "status": "available",
  "environment": "development",
  "version": "1.0.0"
}

Items

Create Item

POST /v1/items
Content-Type: application/json

{
  "name": "Item Name",
  "description": "Item Description",
  "quantity": 10,
  "price": 99.99
}

Get Item

GET /v1/items/{id}

Authentication

(To be implemented)

Register

POST /v1/auth/register

Login

POST /v1/auth/login

Logout

POST /v1/auth/logout

Users

(To be implemented)

Get User Profile

GET /v1/users/{id}

Update User

PUT /v1/users/{id}

File Upload

(To be implemented)

Upload File

POST /v1/upload
Content-Type: multipart/form-data

Development

Available Make Commands

make help          # Show available commands
make run           # Run the application
make build         # Build the application binary
make test          # Run tests
make migrate-up    # Run database migrations up
make migrate-down  # Rollback database migrations
make docker        # Start Docker services
make docker-down   # Stop Docker services
make lint          # Run linter
make swagger       # Generate Swagger documentation

Building

Build the application binary:

make build
# Output: bin/api

Run the binary:

./bin/api -port=8080

Testing

Run all tests:

make test

Run tests with coverage:

go test -cover ./...

Run tests with verbose output:

go test -v ./...

Database Migrations

Create a new migration:

migrate create -ext sql -dir internal/database/migrations -seq migration_name

Run migrations:

make migrate-up

Rollback migrations:

make migrate-down

Configuration

Command-Line Flags

  • -port: Server port (default: 4000)
  • -env: Environment (development|staging|production) (default: development)

Environment Variables

Create a .env file in the project root:

# Database
DATABASE_URL=postgresql://postgres:password@localhost:5432/bmginventory?sslmode=disable

# Server
PORT=4000
ENVIRONMENT=development

# JWT
JWT_SECRET=your-secret-key
JWT_EXPIRY=24h

# OAuth
GOOGLE_CLIENT_ID=your-client-id
GOOGLE_CLIENT_SECRET=your-client-secret

# Storage
UPLOAD_PATH=./uploads
MAX_UPLOAD_SIZE=10485760  # 10MB in bytes

Architecture

Layered Architecture

This project follows a clean architecture pattern with clear separation of concerns:

  1. Handler Layer (internal/handler/): HTTP request/response handling
  2. Service Layer (internal/service/): Business logic
  3. Repository Layer (internal/repository/): Data access
  4. Domain Layer (internal/domain/): Core business entities

Key Patterns

  • Repository Pattern: Abstracts data access logic
  • DTO Pattern: Separates external API contracts from internal models
  • Middleware Pattern: Reusable HTTP middleware components
  • Dependency Injection: Services receive dependencies through constructors

Middleware

Available Middleware

  • CORS: Cross-Origin Resource Sharing configuration
  • Logger: HTTP request/response logging
  • Auth: JWT authentication validation
  • Rate Limit: Request rate limiting per IP/user

Adding Middleware

router := chi.NewRouter()

// Apply middleware
router.Use(middleware.Logger)
router.Use(middleware.RateLimit)
router.Use(middleware.CORS)

// Protected routes
router.Group(func(r chi.Router) {
    r.Use(middleware.Auth)
    r.Get("/protected", protectedHandler)
})

Error Handling

The API uses standard HTTP status codes and returns errors in a consistent format:

{
  "error": {
    "message": "Error description",
    "code": "ERROR_CODE",
    "details": {}
  }
}

Common Status Codes

  • 200 OK: Success
  • 201 Created: Resource created
  • 400 Bad Request: Invalid input
  • 401 Unauthorized: Authentication required
  • 403 Forbidden: Insufficient permissions
  • 404 Not Found: Resource not found
  • 429 Too Many Requests: Rate limit exceeded
  • 500 Internal Server Error: Server error

Security

  • JWT Authentication: Secure token-based authentication
  • Password Hashing: bcrypt for password storage
  • CORS Protection: Configurable CORS policies
  • Rate Limiting: Protection against abuse
  • Input Validation: Comprehensive validation on all inputs
  • SQL Injection Prevention: Parameterized queries via sqlx

Performance Considerations

  • Connection Pooling: Database connection pool management
  • Middleware Ordering: Optimized middleware execution order
  • Context Usage: Proper context propagation for cancellation
  • Timeouts: Configured read/write timeouts

Monitoring & Observability

Health Check

Monitor application health:

curl http://localhost:4000/v1/healthcheck

Logging

The application logs all HTTP requests with:

  • Method and path
  • Status code
  • Response time
  • Request ID

Deployment

Building for Production

# Build optimized binary
go build -ldflags="-s -w" -o bin/api cmd/api/main.go

# Run in production
./bin/api -port=8080 -env=production

Docker Deployment

FROM golang:1.25-alpine AS builder
WORKDIR /app
COPY . .
RUN go build -o api cmd/api/main.go

FROM alpine:latest
COPY --from=builder /app/api /api
EXPOSE 4000
CMD ["/api"]

Contributing

Contributions are welcome! Please follow these steps:

  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

Coding Standards

  • Follow Go best practices and idioms
  • Write tests for new features
  • Update documentation as needed
  • Run go fmt before committing
  • Run make lint to check for issues

Testing

Unit Tests

go test ./internal/...

Integration Tests

go test -tags=integration ./...

Roadmap

  • Complete authentication system
  • User management endpoints
  • File upload functionality
  • Admin dashboard
  • Email notifications
  • Export functionality (CSV, PDF)
  • Advanced search and filtering
  • Real-time updates with WebSockets
  • API documentation with Swagger
  • Performance metrics and monitoring
  • Caching layer (Redis)
  • Background job processing

License

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

Support

For issues, questions, or contributions, please open an issue on GitHub.

Acknowledgments

Contact

Paul Babatuyi - @PaulBabatuyi

Project Link: https://github.com/PaulBabatuyi/BMG-Go-Backend

About

Go backend for BMG-Inventory (React Native), REST API, PostgreSQL,

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages