Skip to content

Go Fiber Backend API โ€‹

HaloLight Go Fiber backend API is built on Fiber 3.0, providing high-performance Go backend service with complete JWT dual-token authentication.

API Documentation: https://halolight-api-go.h7ml.cn/docs

GitHub: https://github.com/halolight/halolight-api-go

Features โ€‹

  • ๐Ÿ” JWT Dual Tokens - Access Token + Refresh Token with auto-renewal
  • ๐Ÿ›ก๏ธ RBAC Permissions - Role-based access control with wildcard matching
  • ๐Ÿ“ก RESTful API - Standardized interface design with OpenAPI documentation
  • ๐Ÿ—„๏ธ GORM 2 - Type-safe database operations
  • โœ… Data Validation - Request parameter validation and error handling
  • ๐Ÿ“Š Logging System - Request logging and error tracking
  • ๐Ÿณ Docker Support - Containerized deployment

Tech Stack โ€‹

TechnologyVersionDescription
Go1.22+Runtime
Fiber3.0Web Framework
GORM2.0Database ORM
PostgreSQL16Data Storage
go-playground/validatorv10Data Validation
JWTgolang-jwt/jwt/v5Authentication
Swagger UI-API Documentation

Quick Start โ€‹

Environment Requirements โ€‹

  • Go >= 1.22
  • PostgreSQL 16 (optional, defaults to SQLite)

Installation โ€‹

bash
# Clone repository
git clone https://github.com/halolight/halolight-api-go.git
cd halolight-api-go

# Install dependencies
go mod download

Environment Variables โ€‹

bash
cp .env.example .env
env
# Database
DATABASE_URL=postgresql://user:pass@localhost:5432/halolight?sslmode=disable

# JWT Secret
JWT_SECRET=your-super-secret-key
JWT_ACCESS_EXPIRES=7d
JWT_REFRESH_EXPIRES=30d

# Service Configuration
PORT=8080
APP_ENV=development

Database Initialization โ€‹

bash
# GORM auto-migration
go run cmd/server/main.go

# Or use Makefile
make migrate

Start Service โ€‹

bash
# Development mode
go run cmd/server/main.go

# Production mode
make build
./bin/server

Visit http://localhost:8080

Project Structure โ€‹

halolight-api-go/
โ”œโ”€โ”€ cmd/
โ”‚   โ””โ”€โ”€ server/
โ”‚       โ””โ”€โ”€ main.go              # Application entry
โ”œโ”€โ”€ internal/
โ”‚   โ”œโ”€โ”€ handlers/                # Controllers/route handlers
โ”‚   โ”‚   โ”œโ”€โ”€ auth_handler.go      # Authentication endpoints
โ”‚   โ”‚   โ”œโ”€โ”€ user_handler.go      # User management
โ”‚   โ”‚   โ”œโ”€โ”€ role_handler.go      # Role management
โ”‚   โ”‚   โ”œโ”€โ”€ permission_handler.go # Permission management
โ”‚   โ”‚   โ”œโ”€โ”€ team_handler.go      # Team management
โ”‚   โ”‚   โ”œโ”€โ”€ document_handler.go  # Document management
โ”‚   โ”‚   โ”œโ”€โ”€ file_handler.go      # File management
โ”‚   โ”‚   โ”œโ”€โ”€ folder_handler.go    # Folder management
โ”‚   โ”‚   โ”œโ”€โ”€ calendar_handler.go  # Calendar events
โ”‚   โ”‚   โ”œโ”€โ”€ notification_handler.go # Notification management
โ”‚   โ”‚   โ”œโ”€โ”€ message_handler.go   # Message management
โ”‚   โ”‚   โ”œโ”€โ”€ dashboard_handler.go # Dashboard statistics
โ”‚   โ”‚   โ””โ”€โ”€ home_handler.go      # Homepage + health check
โ”‚   โ”œโ”€โ”€ services/                # Business logic layer
โ”‚   โ”‚   โ”œโ”€โ”€ auth_service.go
โ”‚   โ”‚   โ”œโ”€โ”€ user_service.go
โ”‚   โ”‚   โ””โ”€โ”€ ...
โ”‚   โ”œโ”€โ”€ models/                  # Data models
โ”‚   โ”‚   โ”œโ”€โ”€ user.go
โ”‚   โ”‚   โ”œโ”€โ”€ role.go
โ”‚   โ”‚   โ””โ”€โ”€ ...
โ”‚   โ”œโ”€โ”€ middleware/              # Middleware
โ”‚   โ”‚   โ”œโ”€โ”€ auth.go
โ”‚   โ”‚   โ””โ”€โ”€ cors.go
โ”‚   โ””โ”€โ”€ routes/                  # Route configuration
โ”‚       โ””โ”€โ”€ router.go
โ”œโ”€โ”€ pkg/
โ”‚   โ”œโ”€โ”€ config/                  # Configuration management
โ”‚   โ”œโ”€โ”€ database/                # Database connection
โ”‚   โ””โ”€โ”€ utils/                   # Utility functions
โ”œโ”€โ”€ docs/                        # Documentation
โ”œโ”€โ”€ .github/workflows/           # GitHub Actions
โ”œโ”€โ”€ Dockerfile                   # Docker configuration
โ”œโ”€โ”€ docker-compose.yml
โ””โ”€โ”€ go.mod

API Modules โ€‹

Authentication Endpoints โ€‹

MethodPathDescriptionPermission
POST/api/auth/loginUser loginPublic
POST/api/auth/registerUser registrationPublic
POST/api/auth/refreshRefresh tokenPublic
POST/api/auth/logoutLogoutAuthenticated
POST/api/auth/forgot-passwordForgot passwordPublic
POST/api/auth/reset-passwordReset passwordPublic
GET/api/auth/meGet current userAuthenticated

User Management Endpoints โ€‹

MethodPathDescriptionPermission
GET/api/usersList usersusers:view
GET/api/users/:idGet user detailsusers:view
POST/api/usersCreate userusers:create
PUT/api/users/:idUpdate userusers:update
DELETE/api/users/:idDelete userusers:delete
PATCH/api/users/:id/statusUpdate user statususers:update
POST/api/users/batch-deleteBatch delete usersusers:delete

Complete Endpoint List โ€‹

Role Management (Roles) - 6 endpoints โ€‹

MethodPathDescription
GET/api/rolesList roles
GET/api/roles/:idGet role details
POST/api/rolesCreate role
PUT/api/roles/:idUpdate role
POST/api/roles/:id/permissionsAssign permissions
DELETE/api/roles/:idDelete role

Permission Management (Permissions) - 4 endpoints โ€‹

MethodPathDescription
GET/api/permissionsList permissions
GET/api/permissions/:idGet permission details
POST/api/permissionsCreate permission
DELETE/api/permissions/:idDelete permission

Team Management (Teams) - 7 endpoints โ€‹

MethodPathDescription
GET/api/teamsList teams
GET/api/teams/:idGet team details
POST/api/teamsCreate team
PATCH/api/teams/:idUpdate team
DELETE/api/teams/:idDelete team
POST/api/teams/:id/membersAdd member
DELETE/api/teams/:id/members/:userIdRemove member

Document Management (Documents) - 11 endpoints โ€‹

MethodPathDescription
GET/api/documentsList documents
GET/api/documents/:idGet document details
POST/api/documentsCreate document
PUT/api/documents/:idUpdate document
PATCH/api/documents/:id/renameRename document
POST/api/documents/:id/moveMove document
POST/api/documents/:id/tagsUpdate tags
POST/api/documents/:id/shareShare document
POST/api/documents/:id/unshareUnshare document
POST/api/documents/batch-deleteBatch delete
DELETE/api/documents/:idDelete document

File Management (Files) - 14 endpoints โ€‹

MethodPathDescription
POST/api/files/uploadUpload file
POST/api/files/folderCreate folder
GET/api/filesList files
GET/api/files/storageGet storage info
GET/api/files/:idGet file details
GET/api/files/:id/download-urlGet download URL
PATCH/api/files/:id/renameRename file
POST/api/files/:id/moveMove file
POST/api/files/:id/copyCopy file
PATCH/api/files/:id/favoriteToggle favorite
POST/api/files/:id/shareShare file
POST/api/files/batch-deleteBatch delete
DELETE/api/files/:idDelete file

Folder Management (Folders) - 5 endpoints โ€‹

MethodPathDescription
GET/api/foldersList folders
GET/api/folders/treeGet folder tree
GET/api/folders/:idGet folder details
POST/api/foldersCreate folder
DELETE/api/folders/:idDelete folder

Message Management (Messages) - 5 endpoints โ€‹

MethodPathDescription
GET/api/messages/conversationsList conversations
GET/api/messages/conversations/:idGet conversation details
POST/api/messagesSend message
PUT/api/messages/:id/readMark as read
DELETE/api/messages/:idDelete message

Notification Management (Notifications) - 5 endpoints โ€‹

MethodPathDescription
GET/api/notificationsList notifications
GET/api/notifications/unread-countGet unread count
PUT/api/notifications/:id/readMark as read
PUT/api/notifications/read-allMark all as read
DELETE/api/notifications/:idDelete notification

Calendar Management (Calendar) - 9 endpoints โ€‹

MethodPathDescription
GET/api/calendar/eventsList events
GET/api/calendar/events/:idGet event details
POST/api/calendar/eventsCreate event
PUT/api/calendar/events/:idUpdate event
PATCH/api/calendar/events/:id/rescheduleReschedule event
POST/api/calendar/events/:id/attendeesAdd attendee
DELETE/api/calendar/events/:id/attendees/:attendeeIdRemove attendee
POST/api/calendar/events/batch-deleteBatch delete
DELETE/api/calendar/events/:idDelete event

Dashboard (Dashboard) - 9 endpoints โ€‹

MethodPathDescription
GET/api/dashboard/statsGet statistics
GET/api/dashboard/visitsGet visit data
GET/api/dashboard/salesGet sales data
GET/api/dashboard/productsGet product data
GET/api/dashboard/ordersGet order data
GET/api/dashboard/activitiesGet activity data
GET/api/dashboard/pieGet pie chart data
GET/api/dashboard/tasksGet task data
GET/api/dashboard/overviewGet overview data

Authentication Mechanism โ€‹

JWT Dual Tokens โ€‹

Access Token:  7 days validity, used for API requests
Refresh Token: 30 days validity, used to refresh Access Token

Request Headers โ€‹

http
Authorization: Bearer <access_token>

Refresh Flow โ€‹

go
// Token refresh example
func RefreshToken(c *fiber.Ctx) error {
    type RefreshRequest struct {
        RefreshToken string `json:"refreshToken"`
    }

    var req RefreshRequest
    if err := c.BodyParser(&req); err != nil {
        return c.Status(400).JSON(fiber.Map{
            "success": false,
            "message": "Invalid request",
        })
    }

    // Validate refresh token
    claims, err := utils.ValidateToken(req.RefreshToken)
    if err != nil {
        return c.Status(401).JSON(fiber.Map{
            "success": false,
            "message": "Invalid refresh token",
        })
    }

    // Generate new access token
    accessToken, err := utils.GenerateAccessToken(claims.UserID)
    if err != nil {
        return c.Status(500).JSON(fiber.Map{
            "success": false,
            "message": "Failed to generate token",
        })
    }

    return c.JSON(fiber.Map{
        "success": true,
        "accessToken": accessToken,
    })
}

Permission System โ€‹

Role Definitions โ€‹

RoleDescriptionPermissions
super_adminSuper Administrator* (all permissions)
adminAdministratorusers:*, documents:*, files:*, teams:*
userRegular Userdocuments:view, documents:create, files:*
guestGuestdashboard:view

Permission Format โ€‹

{resource}:{action}

Examples:
- users:view      # View users
- users:create    # Create users
- users:*         # All user operations
- *               # All permissions

Error Handling โ€‹

Error Response Format โ€‹

json
{
  "success": false,
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Request parameter validation failed",
    "details": [
      { "field": "email", "message": "Invalid email format" }
    ]
  }
}

Error Codes โ€‹

Status CodeError CodeDescription
400VALIDATION_ERRORParameter validation failed
401UNAUTHORIZEDUnauthorized
403FORBIDDENForbidden
404NOT_FOUNDResource not found
409CONFLICTResource conflict
500INTERNAL_ERRORInternal server error

Common Commands โ€‹

bash
# Development
go run cmd/server/main.go

# Build
go build -o bin/server cmd/server/main.go

# Testing
go test ./...

# Database
make migrate

# Code Quality
go vet ./...
golangci-lint run

Deployment โ€‹

Docker โ€‹

bash
docker build -t halolight-api-go .
docker run -p 8080:8080 halolight-api-go

Docker Compose โ€‹

bash
docker-compose up -d
yaml
# docker-compose.yml
version: '3.8'

services:
  app:
    build: .
    ports:
      - "8080:8080"
    environment:
      - APP_ENV=production
      - DATABASE_URL=${DATABASE_URL}
      - JWT_SECRET=${JWT_SECRET}
    restart: unless-stopped

  db:
    image: postgres:16-alpine
    environment:
      POSTGRES_DB: halolight
      POSTGRES_USER: ${DB_USER}
      POSTGRES_PASSWORD: ${DB_PASSWORD}
    volumes:
      - postgres_data:/var/lib/postgresql/data

volumes:
  postgres_data:

Production Configuration โ€‹

env
APP_ENV=production
DATABASE_URL=postgresql://user:pass@host:5432/db
JWT_SECRET=your-production-secret

Testing โ€‹

Run Tests โ€‹

bash
# Unit tests
go test ./...

# Test coverage
go test -coverprofile=coverage.out ./...
go tool cover -html=coverage.out

Test Example โ€‹

go
func TestUserLogin(t *testing.T) {
    app := fiber.New()

    // Setup routes
    app.Post("/api/auth/login", handlers.Login)

    // Prepare test data
    reqBody := `{"email":"test@example.com","password":"password123"}`
    req := httptest.NewRequest("POST", "/api/auth/login", strings.NewReader(reqBody))
    req.Header.Set("Content-Type", "application/json")

    // Execute request
    resp, _ := app.Test(req)

    // Verify response
    assert.Equal(t, 200, resp.StatusCode)
}

Performance Metrics โ€‹

Benchmarks โ€‹

MetricValueConditions
Request Throughput10,000+ QPSSingle machine, 8-core CPU
Average Response Time< 10msSimple queries
Memory Usage~50MBIdle state
CPU Usage< 10%Idle state

Observability โ€‹

Logging System โ€‹

go
// Logging configuration
logger := log.New(os.Stdout, "API: ", log.LstdFlags)

app.Use(func(c *fiber.Ctx) error {
    start := time.Now()
    err := c.Next()
    logger.Printf("%s %s %s %v",
        c.Method(),
        c.Path(),
        c.IP(),
        time.Since(start),
    )
    return err
})

Health Check โ€‹

go
// Health check endpoint
app.Get("/health", func(c *fiber.Ctx) error {
    return c.JSON(fiber.Map{
        "status": "healthy",
        "timestamp": time.Now(),
        "database": db.Ping() == nil,
    })
})

Monitoring Metrics โ€‹

go
// Prometheus metrics
import "github.com/prometheus/client_golang/prometheus"

var (
    requestCounter = prometheus.NewCounterVec(
        prometheus.CounterOpts{
            Name: "api_requests_total",
            Help: "Total API requests",
        },
        []string{"method", "path", "status"},
    )
)

FAQ โ€‹

Q: JWT secret key length requirements? โ€‹

A: JWT secret must be at least 32 characters. Recommend using 64+ character random strings.

bash
# Generate secure key
openssl rand -base64 64

Q: Database connection failed? โ€‹

A: Check database configuration and network connection.

bash
# Check PostgreSQL status
docker-compose ps postgres

# Test connection
psql -h localhost -U postgres -d halolight

Development Tools โ€‹

  • Air - Go hot reload tool
  • golangci-lint - Go code linter
  • goose - Database migration tool
  • mockery - Mock generation tool

Comparison with Other Backends โ€‹

FeatureGo FiberNestJSFastAPISpring Boot
LanguageGoTypeScriptPythonJava
ORMGORMPrismaSQLAlchemyJPA
Performanceโญโญโญโญโญโญโญโญโญโญโญโญโญโญโญโญ
Learning Curveโญโญโญโญโญโญโญโญโญโญโญโญโญ