A robust and scalable Go-based REST API backend for digital membership and loyalty program management. Track customer transactions, award stamp-based rewards, and manage redemptions.
Membership Backend provides a comprehensive backend solution for businesses looking to implement a digital stamp card loyalty program. Customers earn stamps through transactions with sellers, and can redeem accumulated stamps for rewards. Creating an engaging and rewarding customer experience.
# Clone the repository
git clone https://github.com/SeanardK/membership-backend.git
cd membership-backend
# Copy environment file and configure
cp .env.example .env
# Edit .env with your database and Keycloak settings
# Install dependencies and run
go mod download
go run cmd/main.goOr using Docker:
docker-compose up -d- RESTful API Design - Clean and intuitive endpoints following REST principles
- OIDC Authentication - Secure authentication using Keycloak with JWT tokens
- Image Upload - Support for portfolio project image uploads
- PostgreSQL Database - Reliable data persistence with GORM ORM
- Docker Support - Containerized deployment with Docker Compose
- CORS Enabled - Cross-Origin Resource Sharing configuration
- Structured Logging - Comprehensive logging with Logrus
- Auto Migration - Automatic database schema migration on startup
- File Management - Automatic cleanup of associated files on deletion
- Timezone Support - Configured for Asia/Jakarta timezone (UTC storage)
- Requirements
- Tech Stack
- Installation
- Configuration
- Running the Application
- API Endpoints
- Project Structure
- Development
- Docker Deployment
- Authentication
- Troubleshooting
- Contributing
- License
- Go 1.25.4 or higher
- PostgreSQL 13+
- Keycloak Server (for authentication)
- Docker & Docker Compose (optional, for containerized deployment)
- Go - Programming language
- Gin - HTTP web framework
- GORM - ORM library for Go
- PostgreSQL - Relational database
- Keycloak - Identity and access management
- go-oidc - OpenID Connect client
- Logrus - Structured logger
- godotenv - Environment variable loader
- Docker - Containerization platform
-
Clone the repository
git clone https://github.com/SeanardK/go-backend-template cd go-backend-template -
Install dependencies
go mod download
-
Set up environment variables
cp .env.example .env
Edit
.envwith your configuration (see Configuration) -
Run the application
go run cmd/main.go
Create a .env file in the root directory with the following variables:
# Server Configuration
PORT=3001
# Keycloak Configuration
KEYCLOAK_BASE_URL=http://localhost:8080
KEYCLOAK_REALM=your-realm
CLIENT_ID=your-client-id
# Database Configuration
DB_HOST=localhost
DB_PORT=5432
DB_USER=postgres
DB_PASSWORD=your-password
DB_NAME=membership_db
DB_SSLMODE=disable
# CORS Configuration (optional)
# Note: Currently set to allow all origins in development
# ALLOWED_ORIGINS=http://localhost:3000,http://localhost:3001| Variable | Description | Required | Default |
|---|---|---|---|
PORT |
Server port number | No | 3001 |
KEYCLOAK_BASE_URL |
Keycloak server base URL | Yes | - |
KEYCLOAK_REALM |
Keycloak realm name | Yes | - |
CLIENT_ID |
Keycloak client ID | Yes | - |
DB_HOST |
PostgreSQL host | Yes | - |
DB_PORT |
PostgreSQL port | Yes | - |
DB_USER |
Database username | Yes | - |
DB_PASSWORD |
Database password | Yes | - |
DB_NAME |
Database name | Yes | - |
DB_SSLMODE |
PostgreSQL SSL mode | No | disable |
go run cmd/main.gogo build -o portfolio-api cmd/main.go
./portfolio-apiThe server will start on the configured port (default: 3001).
Base URL: http://localhost:3001
All API responses follow a consistent JSON structure:
Success Response:
{
"message": "Operation description",
"data": { /* result data */ }
}Error Response:
{
"message": "Error description",
"error": "Detailed error message (optional)"
}Images are served from:
GET /public/portfolio/images/<filename>
.
βββ cmd/
β βββ main.go # Application entry point
βββ pkg/
β βββ config/
β β βββ connection.go # Database connection configuration
β βββ controller/
β β βββ portfolio.go # Portfolio controller (handlers)
β βββ database/
β β βββ main.go # Database initialization & migration
β βββ middleware/
β β βββ auth.go # Authentication middleware (OIDC)
β βββ model/
β β βββ portfolio.go # Portfolio data model
β βββ routes/
β β βββ index.go # Route registration
β β βββ portfolio.go # Portfolio routes
β βββ utils/
β βββ env.go # Environment variable utilities
β βββ file.go # File upload utilities
βββ public/
β βββ portfolio/
β βββ images/ # Uploaded images storage
βββ basic/ # Basic/example files
βββ docker-compose.yml # Docker Compose configuration
βββ dockerfile # Dockerfile for container build
βββ go.mod # Go module dependencies
βββ go.sum # Dependency checksums
βββ README.md # This file
The application automatically runs database migrations on startup. The schema is defined in the model files.
- Create a model in
pkg/model/ - Create a controller in
pkg/controller/ - Define routes in
pkg/routes/ - Register routes in
pkg/routes/index.go
The application has a maximum multipart memory size of 8MB for file uploads. This is configured in the main application file and can be adjusted as needed.
-
Build and run the container
docker-compose up -d
-
View logs
docker-compose logs -f backend
-
Stop the container
docker-compose down
-
Build the image
docker build -t portfolio-backend . -
Run the container
docker run -d \ -p 3001:3001 \ --env-file .env \ -v $(pwd)/public:/root/public \ --name portfolio-backend \ portfolio-backend
For production deployment, consider:
- Security: Change
AllowAllOriginstofalseand specify allowed origins in CORS configuration - Using a reverse proxy (Nginx, Traefik)
- Setting up SSL/TLS certificates
- Configuring proper CORS origins for your frontend domain
- Using managed PostgreSQL service
- Implementing rate limiting
- Setting up monitoring and logging (e.g., Prometheus, Grafana)
- Using environment-specific configuration
- Implementing health check endpoints
- Securing file upload directory with proper permissions
- Regular database backups
This API uses Keycloak for authentication with OpenID Connect (OIDC). Protected endpoints require a valid JWT token.
- Configure a Keycloak client for your application
- Use the Keycloak authentication endpoints to obtain a token
- Include the token in the
Authorizationheader:Authorization: Bearer <your-jwt-token>
If you encounter database connection errors:
- Verify PostgreSQL is running:
psql -U postgres -l - Check your
.envfile has correct credentials - Ensure the database exists:
CREATE DATABASE membership_db; - Verify SSL mode is set correctly (use
disablefor local development)
If authentication fails:
- Verify Keycloak server is running and accessible
- Check
KEYCLOAK_BASE_URL,KEYCLOAK_REALM, andCLIENT_IDare correct - Ensure your Keycloak client is configured for OIDC
- Verify the JWT token is valid and not expired
If image uploads fail:
- Check the
public/portfolio/images/directory exists and is writable - Verify the file size is under 8MB
- Ensure the content type is set to
multipart/form-data - Check server logs for detailed error messages
If port 3001 is already in use:
- Change the
PORTin your.envfile - Or kill the process using the port:
netstat -ano | findstr :3001(Windows)