zzhuang94/gin-vue-web
About
一个基于 Gin 和 Vue 的企业级全栈 Web 开发框架,专为快速构建现代化管理平台而生。采用前后端分离架构,通过约定优于配置的设计理念,将传统 CRUD 开发效率提升 10 倍以上。 A minimal MVC web framework built with Gin + Vue 3 + Ant Design Vue + Vite, focused on building admin consoles fast.
Web & App DevelopmentMeasured star growth
- in 24h
- 0
- in 7 days
- 0
- in 15 days
- 0
- in 1 month
- Collecting history
Net star changes over overlapping periods, not daily totals. Missing measurements are left blank. Stars measure attention, not software quality.
README_EN.md
Originalgin-vue-web
A minimal MVC web framework built with Gin + Vue 3 + Ant Design Vue + Vite, focused on building admin consoles fast.
🚀 Take off even as a beginner! Just a pinch of Go syntax (being able to define a
structis enough), a little frontend knowledge (html,css,jsbasics), plus a basic understanding ofMySQL, and you are ready for a full-stack journey.🎓 No Vue background? This project is your best practice ground. Learn Vue 3 while doing real work. The framework already wraps the complex logic so you only focus on business.
⚙️ Configuration free! Tedious frontend compilation and bundling are already handled. Ant Design Vue, ECharts, Font Awesome, and other common components are pre-integrated. Just concentrate on core development and forget the annoying config files.
💪 CRUD in three steps! Development? Three quick steps. Deployment? One command. From zero to production faster than writing Hello World.
⚡ Build in 5 minutes, run in 10, finish the first module in 30! No hype—this is the real onboarding experience. 🎯
🌟 Embrace open source with an all-star tech stack! Gin (Go’s hottest web framework) on the backend, Vue 3 (the benchmark progressive framework) on the frontend, and Vite (lightning-fast build tool). All widely adopted, battle-tested technologies. Add whatever you want: plug in ChatGPT, integrate WeChat/Alipay payments, enable real-time chat with WebSocket, create data dashboards with built-in ECharts, or add third-party login via OAuth 2.0. The open-source ecosystem is your toolbox—build anything you imagine. 🚀
Sneak Peek
😎 See the experience before diving into the internals—feel the instant “what you see is what you get” with gin-vue-web.
Feature Demo Video
Your browser will download the video directly. Wait a few seconds and double-click to play.
Feature Screenshots
List page · search/sort/pagination
|
Create modal
|
Edit modal
|
Relation management modal
|
|
Navigation tree
|
Route list
|
Role management
|
Role authorization
|
Profile center
|
Shared component library
|
ECharts sample
|
Icon library |
📋 Table of Contents
- I. Project Introduction
- II. Quick Start
- III. How to Read the Code
- IV. Core Design Philosophy
- 4.1 X Struct - The Core of the Framework
- 4.2 XB Struct - Extension for Batch Operations
- 4.3 Rule Configuration - The Power of Configuration-Driven Development
- 4.4 Route Auto-Registration - The Magic of Zero Configuration
- 4.5 Data Flow Process - Understanding the Whole System
- 4.6 Operation Logging Feature - Data Auditing and Rollback Mechanism
- V. Debugging Methods
- VI. Development Tutorial
- VII. FAQ
- VIII. License
I. Project Introduction
gin-vue-web is an enterprise-grade full-stack web development framework designed for rapidly building modern admin platforms. It adopts a frontend-backend separation architecture, based on the Go and Vue 3 ecosystem, and follows the convention over configuration design philosophy, improving traditional CRUD development efficiency by more than 10x.
1.1 Minimal MVC Architecture
The framework adopts the classic MVC (Model-View-Controller) architecture pattern, reducing boilerplate code in traditional development by more than 80% through intelligent conventions and auto-assembly. Developers only need to focus on business logic, while the framework automatically handles routing, data binding, form validation, and other tedious tasks.
Core Advantages:
- Zero-config startup: No configuration files needed, works out of the box
- Convention over configuration: Follows best practices, reduces decision-making overhead
- Highly extensible: Supports custom middleware, interceptors, and extension points
- Excellent performance: Built on the high-performance Gin framework, easily handles high-concurrency scenarios
1.2 Intelligent Route Auto-Registration
The framework automatically scans Action* methods in Controllers through Go reflection mechanism, achieving zero-configuration automatic route registration. Say goodbye to manually maintaining route tables—just define methods, and routes are automatically generated and registered.
Technical Highlights:
- Reflection scanning: Automatically identifies methods like
ActionIndex,ActionEdit,ActionSave - RESTful style: Automatically generates routes conforming to RESTful standards
- Type safety: Compile-time checks to avoid runtime errors
- Auto documentation: Supports automatic API documentation generation
1.3 Universal CRUD Framework
The framework builds a complete universal CRUD solution around three core files, achieving fully automatic generation from data models to frontend pages.
Core File Architecture:
| File | Responsibility | Tech Stack |
|---|---|---|
backend/g/x.go |
CRUD core logic engine | Go + XORM |
frontend/src/templates/index.vue |
Universal list page template | Vue 3 + Ant Design Vue |
backend/g/rule.go |
Field rule configuration engine | JSON configuration-driven |
Feature Matrix:
| Feature Module | Supported Features | Description |
|---|---|---|
| List Page | Search, sort, pagination, filter | Supports multi-field combined queries |
| Data Operations | Create, edit, delete | Single and batch operations |
| Data Validation | Frontend + backend dual validation | Type checking, required validation, format validation |
| Access Control | Role-based access control | Fine-grained permission management |
1.4 Rule-Driven Development
Through the rule.json configuration file, field rules are defined using a declarative programming approach, achieving true configuration-driven development. Configure once, works across the full stack.
Rule Configuration Capabilities:
- Display rules: Field labels, display order, visibility, formatting methods
- Validation rules: Required validation, type validation, length limits, regular expressions
- Search rules: Exact match, fuzzy search, range queries, IN queries, relational queries
- Interaction rules: Dropdown options, cascading selection, date ranges, file uploads
Advantages:
- Zero-code configuration: No need to write validation logic
- Frontend-backend sync: Configure once, automatically syncs across frontend and backend
- Business focus: Focus on business logic, not technical details
- Rapid iteration: Modify configuration to adjust functionality
1.5 Operation Logging
The framework includes a powerful operation logging (op-log) feature that automatically records all data changes and provides complete audit and rollback capabilities.
Core Features:
- Auto-logging: Automatically records data changes for all configured tables in the core database based on
op.jsonconfiguration - Event Aggregation: Multiple data changes in the same request are automatically aggregated into a single operation event
- Detailed Records: Records operation type (create/update/delete), data table, data ID, and data before/after changes
- Diff Comparison: Intelligently calculates and displays field-level change differences, supports field translation and formatted display
- One-click Rollback: Supports rolling back data to the state before changes, automatically handles dependency checking
- Audit Trail: Records complete audit information including operating user, operation path, operation time, etc.
Use Cases:
- Data Auditing: Track who changed what data and when
- Error Recovery: Quickly roll back mistaken operations and restore data to previous state
- Compliance Requirements: Meet enterprise-level data change auditing and compliance requirements
- Problem Troubleshooting: Quickly locate problem causes through operation history
💡 Detailed Information: For detailed information about how operation logging works, dependency relationship checking mechanism, configuration methods, etc., please refer to 4.6 Operation Logging Feature - Data Auditing and Rollback Mechanism.
1.6 Built-in Enterprise-Grade Features
The framework includes out-of-the-box enterprise-grade base feature modules, covering 90% of common admin system requirements, allowing you to start building business features from day one.
Feature List:
| Feature Module | Technical Implementation | Feature Description |
|---|---|---|
| User Authentication | Session | Supports login, registration, account switching |
| Permission Management | RBAC + Route Guards | Fine-grained permission control based on roles and routes |
| Menu Management | Dynamic menu tree | Supports multi-level menus, icons, permission binding |
| Session Management | Redis distributed sessions | Supports cluster deployment, session sharing |
| Operation Logging | Auto-logging + Rollback | Automatically records data changes, supports viewing details and rollback operations |
| Component Library | Ant Design Vue | 60+ high-quality components, ready to use |
| Chart Library | ECharts | 20+ chart types, supports data visualization |
| Icon Library | Font Awesome | 1000+ icons, meets various scenario needs |
Extension Capabilities:
- Plugin mechanism: Supports custom plugin extensions
- Theme customization: Supports theme switching and custom styles
- Internationalization: Built-in i18n support, easily implement multi-language
- Responsive design: Perfectly adapts to PC, tablet, and mobile devices
II. Quick Start
2.1 Environment Setup
2.1.1 Development Environment Setup
Go Installation:
- Download: https://golang.org/dl/ or https://golang.google.cn/dl/
- Recommended version: Go 1.25.0 and above
- Verify after installation:
go version
Node.js Installation:
- Download: https://nodejs.org/
- Recommended version: Node.js v24.9.0 and above (includes npm)
- Verify after installation:
node -vandnpm -v
2.1.2 Database Setup
MySQL Installation:
- Download: https://dev.mysql.com/downloads/mysql/
- Or use Docker:
docker run -d -p 3306:3306 -e MYSQL_ROOT_PASSWORD=yourpassword mysql:8.0 - Create two database instances
baseandcorefor storing base data and business data respectively - Execute initialization SQL (see
docs/sql/init_base.sqlanddocs/sql/init_core.sql)
2.1.3 Redis Setup
Redis Installation:
- Windows: Download https://github.com/microsoftarchive/redis/releases or use WSL
- Linux/Mac:
sudo apt-get install redis-serverorbrew install redis - Or use Docker:
docker run -d -p 6379:6379 redis:latest - Verify after startup:
redis-cli ping(should returnPONG)
2.1.4 Configuration File
Edit backend/cfg.json and adjust the database and Redis connection to your actual addresses.
2.2 Development Mode
2.2.1 Backend Startup
cd backend
go mod tidy
go build
./backend
The backend runs on http://localhost:3000 by default.
2.2.2 Frontend Startup
cd frontend
npm install
npm run dev -- --host 0.0.0.0
The frontend runs on http://localhost:5173 and http://{real-server-IP}:5173 by default.
2.2.3 Login to System
It is recommended to use http://{real-server-IP}:5173 to log in. Admin credentials: admin/Admin321!
2.3 Production Deployment Guide
For detailed deployment instructions, including production environment configuration, Nginx configuration, Docker deployment, etc., please refer to the Deployment Documentation.
III. How to Read the Code
3.1 Project Structure Overview
gin-vue-web adopts a classic frontend-backend separation architecture. Understanding this architecture is the first step in reading the code.
What does frontend-backend separation mean?
Simply put, the frontend (Vue 3) and backend (Go) are two completely independent applications. They communicate through HTTP APIs, with the frontend responsible for display and interaction, and the backend responsible for data processing and business logic. The benefit of this architecture is that frontend and backend can be developed, deployed, and maintained independently.
Project Directory Structure
gin-vue-web/
├── backend/ # Backend code (Go)
│ ├── api/ # RESTful API directory
│ │ ├── frm/ # API framework code
│ │ │ ├── common.go # Common response functions
│ │ │ └── middleware.go # API middleware
│ │ ├── modules/ # API business modules
│ │ │ └── res/ # res module APIs
│ │ │ ├── ip.go
│ │ │ ├── service.go
│ │ │ ├── policy.go
│ │ │ └── vidc.go
│ │ └── router.go # API route configuration
│ │
│ ├── web/ # Web interface directory
│ │ ├── frm/ # Web framework code
│ │ │ ├── x.go # CRUD core logic (X struct)
│ │ │ ├── xb.go # Batch operation extension (XB struct)
│ │ │ ├── action.go # Route auto-registration
│ │ │ ├── web.go # Web base functionality
│ │ │ ├── middleware.go # Web middleware
│ │ │ └── ...
│ │ ├── modules/ # Web business modules
│ │ │ ├── base/ # Base module (users, roles, etc.)
│ │ │ │ ├── action.go
│ │ │ │ ├── user.go
│ │ │ │ └── ...
│ │ │ └── res/ # Resource module (example)
│ │ │ ├── ip.go
│ │ │ ├── service.go
│ │ │ └── ...
│ │ └── router.go # Web route configuration
│ │
│ ├── models/ # Shared data models (used by both api and web)
│ │ ├── base/ # base module models
│ │ │ ├── user.go
│ │ │ ├── role.go
│ │ │ └── ...
│ │ └── res/ # res module models
│ │ ├── ip.go
│ │ ├── service.go
│ │ └── ...
│ │
│ ├── g/ # Shared utilities (used by both api and web)
│ │ ├── cfg.go # Configuration management
│ │ ├── model.go # Base model
│ │ ├── rule.go # Rule configuration processing
│ │ └── op.go # Operation logging
│ │
│ ├── libs/ # Utility libraries
│ ├── main.go # Entry file
│ ├── rule.json # Field rule configuration
│ └── op.json # Operation log configuration
│
├── frontend/ # Frontend code (Vue 3)
│ ├── src/
│ │ ├── components/ # Common components
│ │ │ ├── searcher.vue # Searcher
│ │ │ ├── table.vue # Data table
│ │ │ ├── pager.vue # Pagination
│ │ │ ├── edit.vue # Edit form
│ │ │ └── ...
│ │ ├── modules/ # Business pages
│ │ ├── templates/ # Page templates
│ │ │ ├── index.vue # Universal list page template
│ │ │ ├── layout.vue # Layout template
│ │ │ └── ...
│ │ ├── libs/ # Utility libraries
│ │ │ └── lib.ts # Core utility functions
│ │ └── app.vue # Root component
│ └── package.json
│
└── docs/ # Documentation
3.2 Backend Code Structure
The backend adopts a dual architecture design, completely separating RESTful API and Web interface while sharing data models and base utilities.
3.2.1 API Directory (backend/api/) - RESTful API
The API directory provides standard RESTful API interfaces, using a functional programming approach that is simple and direct.
Directory Structure:
api/frm/: API framework codecommon.go: Common response functions (Success, Error, pagination, etc.)middleware.go: API middleware (authentication, logging, etc.)
api/modules/: API business modulesres/: res module API handlersip.go: IP-related APIs (GetIpList, GetIpById)service.go: Service-related APIspolicy.go: Policy-related APIsvidc.go: Vidc-related APIs
api/router.go: API route configuration
Features:
- ✅ Stateless, pure function implementation
- ✅ Standard RESTful response format
- ✅ Uses HTTP status codes (200, 400, 404, 500)
- ✅ Suitable for external system calls and mobile apps
3.2.2 Web Directory (backend/web/) - Web Interface
The Web directory provides Web interface-related controllers, using an object-oriented approach that inherits framework base classes for rich functionality.
Directory Structure:
web/frm/: Web framework codex.go: CRUD core logic (X struct)xb.go: Batch operation extension (XB struct)action.go: Route auto-registrationweb.go: Web base functionalitymiddleware.go: Web middleware (Session, permissions, etc.)
web/modules/: Web business modulesbase/: Base module (users, roles, etc.)res/: Resource module (example)
X Struct Core Features:
DB: Database connection, used to execute SQL queriesModel: Data model, defines the structure of the data table to be operated onRules: Field rules, loaded fromrule.json, controls field display, validation, search, and other behaviorsTool: Toolbar button configuration, such as the "Add" buttonOption: Row operation button configuration, such as "Edit" and "Delete" buttons for each rowAndWheres: Fixed query conditions, such as only showing published dataWrapData: Data processing function, can perform custom processing before returning dataDump: When enabled, shows an "Export" button on the list page so users can export the current search result set to Excel
XB Struct:
XB is an extended version of X, specifically designed to support batch operations. It will automatically add "Batch Modify" and "Batch Delete" buttons to the toolbar.
Features:
- ✅ Stateful, contains DB, Model, Rules, and other configurations
- ✅ Automatic CRUD, batch operations, page rendering
- ✅ Automatic route registration via reflection
- ✅ Suitable for complex Web interfaces
3.2.3 Shared Resources
models/ - Shared Data Models
All data models are unified in the models/ directory and shared by both api and web:
models/base/: base module models (user.go, role.go, etc.)models/res/: res module models (ip.go, service.go, etc.)
g/ - Shared Utilities
Provides shared functionality such as configuration management, rule processing, operation logging:
cfg.go: Configuration managementrule.go: Rule configuration processing (loads and parsesrule.json)model.go: Base model interfaceop.go: Operation logging functionality
libs/ - Utility Libraries
Provides underlying utility functions for database, logging, Redis, strings, etc.
3.2.4 Comparison of Two Architectures
| Feature | API (Functional) | Web (Object-Oriented) |
|---|---|---|
| Code Organization | Package-level functions | Struct + methods |
| State Management | Stateless | Stateful (reusable configuration) |
| Feature Richness | Basic CRUD | Auto CRUD + batch operations + page rendering |
| Route Registration | Manual registration | Auto registration (reflection) |
| Use Cases | RESTful API | Web interface |
Design Advantages:
- ✅ Separation of Concerns: API and Web each have their own responsibilities
- ✅ Code Reuse: Shared models and g, avoiding duplicate code
- ✅ Flexible Extension: Can choose different implementation approaches based on needs
- ✅ Easy Maintenance: Clear structure, convenient for team collaboration
3.3 Frontend Code Structure
3.3.1 Core Files
app.vue - Root Component
This is the entry point of the entire frontend application. It listens for route changes, and when users access different pages, it calls backend APIs to get page configuration, then dynamically loads the corresponding Vue components. This design allows pages to be completely controlled by the backend, with the frontend only responsible for rendering.
libs/lib.ts - Core Utility Functions
This file provides the most commonly used utility functions in the frontend:
curl(): Calls backend APIs, automatically adds/webprefix, handles requests and responsesloadModal(): Loads modal components, used for edit, create, and other popup operationsloadComponent(): Dynamically loads Vue componentssmartUrl(): Intelligently processes URLs, converts relative paths to absolute paths
These functions encapsulate the details of frontend-backend interaction, allowing you to focus on business logic.
templates/index.vue - Universal List Page Template
This is the universal list page template provided by the framework. It automatically generates search forms, data tables, pagination components, etc., based on the rule configuration returned by the backend. You don't need to write this code for every list page—the framework has already done it for you.
3.3.2 Component System
The framework provides a series of reusable common components:
searcher.vue: Searcher component, automatically generates search forms based on rulestable.vue: Data table component, supports sorting, selection, row operationspager.vue: Pagination componentedit.vue: Edit form component, automatically generates form fields based on rulesbutton.vue: Button component, supports different types of button styles
These components are all built on Ant Design Vue, providing a unified UI style and interaction experience.
3.4 Code Reading Suggestions
Reading code is a gradual process. It's recommended to follow this order:
Step 1: Start from the Entry Point
Understanding the application startup flow is important. The backend starts from main.go, which initializes the database, loads configuration, and registers routes. The frontend starts from main.ts, which creates the Vue application, registers routes, and mounts to the DOM.
Step 2: Understand the Core Framework
Focus on reading backend/g/x.go, which is the core of the entire framework. Understanding how the X struct works and what each of its methods does is key to understanding the entire framework.
At the same time, understand how rule.json drives frontend forms and backend validation. This is the embodiment of the framework's "configuration-driven" philosophy.
Step 3: Trace the Data Flow
Choose a specific feature (such as list query) and trace how data flows from the frontend request:
- Frontend initiates request
- Backend receives request
- Build query conditions
- Execute database query
- Process returned data
- Return to frontend
- Frontend updates interface
Understanding this flow will help you understand how the entire system works.
Step 4: Review Example Code
Refer to example code in modules/base/ and modules/res/. These are actual working code that can help you understand how to use the framework in real projects.
IV. Core Design Philosophy
4.1 X Struct - The Core of the Framework
The X struct is the core of the entire framework. Understanding it is key to understanding the entire framework.
4.1.1 Design Philosophy: Convention over Configuration
The framework adopts the "convention over configuration" design philosophy. This means the framework defines a set of conventions, and as long as you follow these conventions, the framework can automatically complete most of the work for you.
For example, you only need to:
- Define data models (Model)
- Configure field rules (rule.json)
- Create a Controller and inherit
X
The framework will automatically generate for you:
- List page
- Search functionality
- Create functionality
- Edit functionality
- Delete functionality
You don't need to write a lot of boilerplate code—the framework has already done it for you.
4.1.2 Core Methods of the X Struct
The X struct provides five core methods, corresponding to the five CRUD operations:
ActionIndex - List Page Rendering
When a user accesses the list page, this method is called. It will:
- Load field rules from
rule.json - Build toolbar buttons and row operation buttons
- Get URL parameters (for search conditions)
- Render the frontend template, passing all configuration information
The frontend template will automatically generate search forms, data tables, and other components based on these configurations.
ActionFetch - Data Retrieval
This is the core method for retrieving data on the list page. When users search, sort, or paginate, the frontend calls this method.
Its workflow is:
- Receive search parameters, sort parameters, and pagination parameters from the frontend
- Build SQL query conditions based on the
searchconfiguration inrule.json - Execute database queries to get total count and data list
- Call
WrapDatato process data (e.g., translate foreign key IDs to display names) - Return data in JSON format to the frontend
ActionEdit - Edit Page Rendering
When a user clicks the "Add" or "Edit" button, this method is called. It will:
- Determine if it's create or edit (via the
idin URL parameters) - If editing, load existing data from the database
- Load field rules from
rule.json - Render the edit form template, passing data and rules
The frontend template will automatically generate form fields based on rules, including input boxes, dropdown selections, multi-line text, etc.
ActionSave - Data Saving
When a user submits a form, this method is called. It will:
- Determine if it's create or edit
- Parse data from the request body
- Validate required fields based on the
requiredconfiguration inrule.json - Handle special fields (e.g., JSON fields, delimiter fields)
- Save to the database (using transactions to ensure data consistency)
- Return success or failure information
ActionDelete - Data Deletion
When a user clicks the "Delete" button, this method is called. It will:
- Get the data ID to delete from URL parameters
- Query the database to check if the data exists
- Call the model's
Deletemethod to delete data (using transactions) - Return success information
4.1.3 Building Query Conditions
The buildCondition method is responsible for building SQL query conditions based on search parameters. This is a typical example of the framework's "rule-driven" approach.
The framework will decide how to build query conditions based on each field's search configuration in rule.json:
search: 0: No search, ignore this fieldsearch: 1: Exact match, generatesWHERE field = valuesearch: 2: Fuzzy search, generatesWHERE field LIKE '%value%'search: 3: IN query, generatesWHERE field IN (value1, value2, ...)
This way, you only need to configure the search type in rule.json, and the framework will automatically handle it without writing SQL code.
4.2 XB Struct - Extension for Batch Operations
XB is an extended version of X, specifically designed to support batch operations.
4.2.1 Why XB is Needed
In real business scenarios, it's often necessary to perform batch operations on multiple records. For example, batch status modification, batch deletion, etc. If you use X, you need to implement these features yourself. XB has already implemented them for you.
4.2.2 XB Design
XB uses Go's generics feature to ensure type safety. It inherits from X, so it has all the functionality of X, while adding three new methods:
ActionBatchEdit: Batch edit, displays a form where you can select fields to modifyActionBatchSave: Batch save, applies modifications to selected multiple recordsActionBatchDelete: Batch delete, deletes selected multiple records
4.2.3 Benefits of Using XB
When you use XB, the framework will automatically:
- Add "Batch Modify" and "Batch Delete" buttons to the toolbar
- Enable multi-select functionality in the table
- Register routes for batch operations
You don't need to write any additional code—just change g.X to g.XB.
4.3 Rule Configuration - The Power of Configuration-Driven Development
rule.json is the core configuration file of the framework, defining field rules for each table. This embodies the framework's "configuration-driven" philosophy.
4.3.1 Role of Rule Configuration
Through rule.json, you can define:
- Field display names (for form labels, table column headers)
- Whether fields are required (for form validation)
- Field search types (for building query conditions)
- Field dropdown options (for generating dropdown select boxes)
- Field translation rules (for converting foreign key IDs to display names)
- Field validation rules (for enforcing type, range, and pattern checks before saving)
The framework will automatically generate frontend forms and backend validation logic based on these rules—you don't need to write code.
4.3.2 Field Descriptions in Rule Configuration
Basic Fields
key: Field name, corresponding to the database table column namename: Display name, used for form labels and table column headersrequired: Whether required,truemeans this field must be filled when savingreadonly: Whether readonly,truemeans this field cannot be edited in the edit pagedefault: Default value, automatically filled when creating new data
Search Configuration
The search field controls the search behavior of this field on the list page:
0: No search, this field will not appear in the search form1: Exact match, usesWHERE field = valuewhen searching2: Fuzzy search, usesWHERE field LIKE '%value%'when searching3: IN query, supports selecting multiple values, usesWHERE field IN (value1, value2, ...)when searching
Display Configuration
textarea: Whether multi-line text input,trueuses<textarea>,falseuses<input>json: Whether JSON field, needs to settextarea: trueat the same time, framework will automatically validate and format JSONbold: Whether bold display, used for table columnshide: Whether hidden in table,truemeans this field is not displayed in the tablewidth: Column width, used for table columns
Dropdown Option Configuration
The limit field is used to define dropdown option lists. Each option contains:
key: Option value (value stored in database)label: Option display text (text seen by users)badge: Option badge style (for table display, such as "success", "danger", etc.)
Translation Configuration (Trans)
- Validation Configuration
- The
validationfield lets you attach rich validation logic to any rule. You can require integer/float values, define min/max ranges, limit input to valid IP/IPv4/IPv6 formats, or provide custom regular expressions. All validations run insideActionSave, ensuring invalid payloads never reach the database.
The trans field is used to convert foreign key IDs to display names. This is very useful in relational queries.
For example, an article table has a category_id field that stores the category ID. But when displaying, we want to show the category name instead of the ID.
By configuring trans, the framework will automatically query the category table and convert IDs to names. If the data volume is large, you can set ajax: true to use AJAX for dynamically loading options.
4.3.3 Rule Loading Mechanism
The framework calls initRules() at startup to load the rule.json file and parse it into an in-memory data structure. When creating an X struct, it will look up the corresponding configuration from the rules based on the model's table name (TableName()).
When needed, the framework calls the SelfWrap() method to process rules, such as:
- Processing dropdown options, generating option lists and mappings
- Processing translation configuration, if in non-AJAX mode, queries the database to generate option lists
4.4 Route Auto-Registration - The Magic of Zero Configuration
Route auto-registration is a major feature of the framework, eliminating the need to manually maintain route tables.
4.4.1 How It Works
The framework uses Go's reflection mechanism to automatically scan all methods starting with Action in all Controllers, then automatically registers them as routes.
The workflow is:
- You call
RegController()to register a Controller - The framework uses reflection to get all methods of the Controller
- Filters methods starting with
Action - Converts method names to route paths (camelCase to kebab-case)
- Registers as POST routes
4.4.2 Route Rules
The route format is: /{module}/{controller}/{action}
For example:
ActionIndex→/res/service/indexActionFetch→/res/service/fetchActionBatchEdit→/res/service/batch-edit
4.4.3 Method Naming Conventions
Method names must follow these conventions:
- Must start with
Action - Use camelCase naming (e.g.,
ActionBatchEdit) - Accept
*gin.Contextparameter
As long as you follow these conventions, the framework can automatically identify and register routes.
4.4.4 Route Table Management
The framework also automatically saves registered routes to the action table in the database. This table is used for permission management, controlling which users can access which routes.
4.5 Data Flow Process - Understanding the Whole System
Understanding how data flows between frontend and backend is key to understanding the entire system.
4.5.1 Complete Data Flow (Taking List Page as Example)
Let's trace a complete request flow:
Step 1: User Accesses Page
User enters a URL in the browser, such as /res/service/index.
Step 2: Frontend Route Handling
Vue Router captures route changes, and the app.vue component listens for route changes.
Step 3: Frontend Calls Backend API
app.vue calls lib.curl('/res/service/index'), and lib.ts automatically adds the /web prefix, ultimately requesting POST /web/res/service/index.
Step 4: Backend Route Matching
The Gin framework matches the corresponding route and finds the ActionIndex method of the Service Controller.
Step 5: Backend Processes Request
The X.ActionIndex() method is called:
- Load field rules from
rule.json - Build toolbar buttons and row operation buttons
- Get URL parameters (for search conditions)
- Render the frontend template
templates/index.vue, passing all configurations
Step 6: Frontend Renders Page
The frontend receives page configuration and dynamically loads the templates/index.vue template. The template automatically generates based on rules:
- Search form (based on
searchconfiguration) - Data table (based on field rules)
- Toolbar buttons
- Row operation buttons
Step 7: Frontend Retrieves Data
After the page is rendered, templates/index.vue automatically calls lib.curl('fetch', params) to get data. Requests POST /web/res/service/fetch.
Step 8: Backend Queries Data
The X.ActionFetch() method is called:
- Parse request parameters (search, sort, pagination)
- Build query conditions based on the
searchconfiguration inrule.json - Execute database query
- Call
WrapDatato process data (translate foreign keys, etc.) - Return data in JSON format
Step 9: Frontend Updates Interface
The frontend receives data, updates reactive variables, and Vue automatically re-renders the table to display data.
4.5.2 Details of Search Flow
When a user enters content in the search box and clicks search:
- Frontend collects values of all search fields, forming an object
- Calls
lib.curl('fetch', {arg: searchParams, sort: sortParams, page: pageParams}) - Backend
ActionFetchreceives parameters - Iterates through search parameters, for each field:
- Finds corresponding rule configuration
- Builds query conditions based on
searchtype - Exact match uses
WHERE field = value - Fuzzy search uses
WHERE field LIKE '%value%' - IN query uses
WHERE field IN (value1, value2, ...)
- Executes SQL query
- Returns result data
4.5.3 Details of Save Flow
When a user fills out a form and clicks save:
- Frontend collects form data, forming an object
- Calls
lib.curl('save', formData)orlib.curl('save?id=123', formData)(when editing) - Backend
ActionSavereceives request - Determines if it's create or edit (via
idin URL parameters) - If editing, first loads existing data from database
- Parses request body, deserializes JSON data to model
- Validates required fields based on
requiredconfiguration inrule.json - Handles special fields:
- JSON fields: Validate and format JSON
- Delimiter fields: Process multi-line text, remove delimiters
- Calls model's
Savemethod to save to database (using transactions) - Returns success or failure information
4.6 Operation Logging Feature - Data Auditing and Rollback Mechanism
The framework includes a powerful operation logging (op-log) feature that automatically records all data changes and provides complete audit and rollback capabilities.
4.6.1 Core Features
- Auto-logging: Automatically records data changes for all configured tables in the core database based on
op.jsonconfiguration - Event Aggregation: Multiple data changes in the same request are automatically aggregated into a single operation event
- Detailed Records: Records operation type (create/update/delete), data table, data ID, and data before/after changes
- Diff Comparison: Intelligently calculates and displays field-level change differences, supports field translation and formatted display
- One-click Rollback: Supports rolling back data to the state before changes, automatically handles dependency checking
- Audit Trail: Records complete audit information including operating user, operation path, operation time, etc.
4.6.2 How It Works
- Configure tables to be logged in
op.json(core database only) - Framework automatically detects and records changes when data is saved/deleted
- Multiple changes in the same request are linked via UUID and aggregated into one operation event
- Operation events are stored in the
op_eventtable in thebasedatabase - Detailed change information is stored in the
op_logtable in thebasedatabase
4.6.3 Dependency Relationship Checking Mechanism
The framework automatically checks data dependency relationships before rollback operations to ensure data consistency. This is a core design of the operation logging feature, preventing data inconsistency issues caused by rollbacks.
Why Dependency Checking is Needed:
Database changes must follow primary key-foreign key dependency relationships, otherwise data inconsistency will occur. For example: if b.a_id = a.id (table b's foreign key references table a's primary key), then data b must be deleted before deleting data a, otherwise data b will not be able to map to a valid primary key, causing data inconsistency.
Three Types of Dependency Relationships:
Consecutive Changes to the Same Record
- Scenario: The same record undergoes multiple consecutive changes, such as
a -> b -> c - Rule: If rolling back
a -> b, operationb -> cmust also be rolled back, because operation 2 depends on the result of operation 1 - Example: A user first changes an order status to "Paid", then changes it to "Shipped". When rolling back the "Paid" status, the "Shipped" status must also be rolled back
- Scenario: The same record undergoes multiple consecutive changes, such as
Primary Key Dependency (Newly Created Data is Referenced)
- Scenario: Operation 1 creates data a, operation 2 modifies (or creates) data b, after which
b.a_id = a.id - Rule: If rolling back operation 1 (deleting newly created a), operation 2 must also be rolled back, because operation 2 depends on the primary key created by operation 1
- Example: First create category A (id=100), then create article B with
category_id=100. When rolling back the creation of category A, the creation of article B must also be rolled back
- Scenario: Operation 1 creates data a, operation 2 modifies (or creates) data b, after which
Foreign Key Dependency (Deleting Referenced Data)
- Scenario: Operation 1 modifies (or deletes) data b, before which
b.a_id = a.id; operation 2 deletes data a - Rule: If rolling back operation 1, operation 2 must also be rolled back, otherwise
b.a_idwill not be able to map to a valid primary key - Example: First modify an order's customer ID to 200, then delete customer 200. When rolling back the order modification, the customer deletion must also be rolled back, otherwise the order's customer ID will point to a non-existent record
- Scenario: Operation 1 modifies (or deletes) data b, before which
4.6.4 Configuration Method
Configure primary key-foreign key relationships in op.json using the primary field:
{
"table_a": {
"name": "Table A",
"db": "core",
"show": ["field1", "field2"],
"primary": {
"id": {
"table_b": "a_id",
"table_c": "a_id"
}
}
}
}
Configuration Description:
primary: Defines which tables' foreign keys reference this table's primary key"id": Primary key field name"table_b": "a_id": Table table_b's foreign key fielda_idreferences table table_a's primary keyid
4.6.5 Checking Process
- User selects operation events to rollback
- Framework calls
CheckRely()to recursively check all dependency relationships - If dependencies are found, automatically collects all operation events that need to be rolled back together
- Frontend displays the complete rollback list, user confirms before unified rollback
- All rollback operations are executed in the same transaction to ensure atomicity
4.6.6 Design Advantages
- Automation: No need to manually analyze dependency relationships, framework automatically detects
- Safety: Prevents data inconsistency issues caused by rollbacks
- Completeness: Recursive checking ensures all related operations are properly handled
- Transparency: Clearly displays all operations that need to be rolled back, user can confirm before execution
4.6.7 Use Cases
- Data Auditing: Track who changed what data and when
- Error Recovery: Quickly roll back mistaken operations and restore data to previous state
- Compliance Requirements: Meet enterprise-level data change auditing and compliance requirements
- Problem Troubleshooting: Quickly locate problem causes through operation history
V. Debugging Methods
5.1 Locating Backend Code from Browser Requests
In actual development, you often need to find the corresponding backend code based on browser requests. This is a very important debugging skill.
5.1.1 Step 1: View Network Requests
Open browser developer tools (press F12), switch to the Network tab. When you perform operations (such as search, save), you'll see a list of network requests. Find the corresponding request and click to view details.
5.1.2 Step 2: Parse Request URL
The framework's request format is: POST /web/{module}/{controller}/{action}
For example, if you see POST /web/res/service/fetch, you can parse:
module:rescontroller:serviceaction:fetch
5.1.3 Step 3: Locate Backend Code
Based on the parsed information, you can quickly locate the code:
For Web Requests (/web/...):
- Find Controller Registration
Search for RegController("res", "service" in backend/web/router.go to find the registration code.
- Find Controller File
Based on module and controller names, find the file: backend/web/modules/res/service.go
- Find Action Method
If the Controller inherits from web/frm.X or web/frm.XB, the ActionFetch method is in backend/web/frm/x.go. If it's a custom method, it's in the Controller file.
For API Requests (/api/...):
- Find Route Registration
Find the corresponding route configuration in backend/api/router.go.
- Find Handler Function
Based on the route path, find the corresponding handler function file: backend/api/modules/res/service.go
5.1.4 Step 4: Add Debug Code
After finding the code, you can add logs or breakpoints for debugging:
Using Logs for Debugging
Add logrus.Infof() in the code to output key information, such as parameter values, query conditions, etc. This is the simplest and most direct debugging method.
Using Debugger
If using GoLand or VS Code, you can set breakpoints for debugging. This is the most powerful debugging method, allowing you to view variable values, step through execution, etc.
5.2 Locating Vue Components from Page Elements
Sometimes you need to find the corresponding Vue component code based on elements on the page.
5.2.1 Step 1: Use Browser Developer Tools
Open developer tools, use the element selector (Ctrl+Shift+C or click the icon in the top left), then click on elements on the page.
5.2.2 Step 2: View Vue Components
If you have the Vue DevTools extension installed (highly recommended), you can:
- Switch to the Vue tab
- Select an element to view the corresponding component
- View the component's props, data, methods, etc.
Vue DevTools is the best tool for debugging Vue applications, clearly showing component trees, reactive data, event triggers, etc.
5.2.3 Step 3: Locate Component Files
By Component Name
If you see a component name in Vue DevTools, such as Searcher, the corresponding file is frontend/src/components/searcher.vue.
By Template Path
In templates/index.vue, you can see which components are used, such as <Searcher>, <Table>, etc.
By Source Maps
In the browser's Sources tab, you can find files starting with webpack:// or vite://, which correspond to the frontend/src/ directory.
5.2.4 Step 4: Add Debug Code
Add console.log() in the component to output key information, or use Vue DevTools' breakpoint functionality.
5.3 Common Debugging Scenarios
5.3.1 Scenario 1: Search Not Working
If search functionality doesn't work, check the following steps:
- Check rule.json Configuration
Ensure the field's search configuration is not 0. If search: 0, this field will not appear in the search form.
- Check Frontend Request Parameters
Add console.log() in the fetchData method of templates/index.vue to check if search parameters are correctly passed.
- Check Backend Query Conditions
Add logs in the buildCondition method of x.go to check if the built query conditions are correct.
5.3.2 Scenario 2: Save Failed
If save functionality fails, check the following:
- Check Required Fields
Ensure all fields marked as required: true in rule.json have values.
- Check Backend Validation
Add logs in the parsePayload method of x.go to view parsed data and validation errors.
- Check Database Constraints
Use SQL tools to view table structure, check if there are NOT NULL constraints or other constraints causing save failures.
5.3.3 Scenario 3: Dropdown Options Not Displaying
If dropdown options don't display, check:
- Check rule.json Configuration
Ensure limit or trans configuration is correct.
- Check Translation Configuration
If using trans, ensure table names and field names are correct, and there is data in the database.
- Check Database Data
Use SQL queries to confirm there is data in the related table.
5.3.4 Scenario 4: Route 404
If accessing a page returns 404, check:
- Check Controller Registration
Ensure RegController() and BindActions() are called in router.go.
- Check Method Name
Ensure method names start with Action and use camelCase naming.
- Check Route Table
Query the action table in the database to confirm routes are registered.
VI. Development Tutorial
6.1 Adding a Regular Page
Sometimes you need to create a simple page that doesn't involve database operations, such as help pages, about pages, etc.
Important: Route Convention
The framework requires a three-level route structure: {module}/{controller}/{action}. Frontend file paths must also follow this convention.
6.1.1 Step 1: Create Frontend Page
Frontend file paths must follow the three-level structure: frontend/src/modules/{module}/{controller}/{action}.vue
For example, to create route /example/help/index, you need to create the file:
frontend/src/modules/example/help/index.vue
The page content is just a regular Vue component and can contain any content.
6.1.2 Step 2: Create Backend Controller
Create a controller file under backend/web/modules/{module}/.
For example, for route /example/help/index, you need to create:
backend/web/modules/example/help.go
The Controller needs to inherit web/frm.Web (not web/frm.X, because CRUD functionality is not needed).
Define an ActionIndex method that calls Render() to render the frontend page.
6.1.3 Step 3: Register Route
Call RegController() in backend/web/router.go to register the Controller.
When registering, you need to specify three parameters: module, controller, and instance.
For example: frm.RegController("example", "help", controllers.NewHelp())
Then call BindActions() to bind routes.
6.1.4 Step 4: Access Page
After starting the service, access the corresponding URL to see the page. The route address is /example/help/index.
6.2 Adding a CRUD Feature Set
This is the core functionality of the framework. You can complete a full CRUD feature set in just three steps.
6.2.1 Step 1: Define Data Model
Create a Model file under backend/models/{module}/ and define the data structure. The Model needs to:
- Inherit
g.Model(includes id, created, updated fields) - Define business fields
- Implement four methods of the
ModelXinterface:TableName(),New(),Save(),Delete()
For example: backend/models/res/service.go
6.2.2 Step 2: Configure Field Rules
Add table configuration in rule.json. Configure for each field:
key: Field namename: Display namerequired: Whether requiredsearch: Search type- Other needed configurations (such as dropdown options, translations, etc.)
6.2.3 Step 3: Create Controller
Web Controller (Recommended for Web Interface):
Create a Controller file under backend/web/modules/{module}/ that inherits web/frm.X (or web/frm.XB if batch operations are needed). The framework will automatically provide all CRUD functionality.
For example: backend/web/modules/res/service.go
If customization is needed, you can configure Tool (toolbar buttons) and Option (row operation buttons).
API Handler (For RESTful API):
Create a handler function file under backend/api/modules/{module}/ using response functions from the api/frm package.
For example: backend/api/modules/res/service.go
6.2.4 Step 4: Register Route and Create Database Table
Web Routes: Register the Controller in backend/web/router.go, then call BindActions() to bind routes.
API Routes: Register routes in backend/api/router.go.
Then execute SQL to create the database table.
6.2.5 Step 5: Enable Operation Logging (Optional)
If you need to enable operation logging, add table configuration in backend/op.json:
{
"your_table_name": {
"name": "Table Display Name",
"db": "core",
"show": ["field1", "field2", "field3"],
"primary": {
"id": {
"related_table1": "foreign_key_field1",
"related_table2": "foreign_key_field2"
}
}
}
}
Configuration Description:
name: Table display name, used for operation log displaydb: Database name, must be"core"(operation logging only records tables in the core database)show: List of fields to display in operation logs, used for diff comparison displayprimary: Primary key relationships, defining which tables' foreign keys reference this table's primary key"id": Primary key field name (usuallyid)"related_table1": "foreign_key_field1": Indicates thatrelated_table1table'sforeign_key_field1field references this table's primary keyid- Multiple related tables can be configured, each on a separate line
Configuration Example:
Assume the following table structure:
categorytable (primary key:id)articletable (foreign key:category_idreferencescategory.id)tagtable (foreign key:category_idreferencescategory.id)
When configuring the category table in op.json:
{
"category": {
"name": "Category",
"db": "core",
"show": ["name", "status"],
"primary": {
"id": {
"article": "category_id",
"tag": "category_id"
}
}
}
}
After this configuration, the framework will automatically check dependency relationships during rollback operations:
- If rolling back a category creation operation, it will automatically check if any articles or tags reference that category
- If rolling back a category deletion operation, it will automatically check if any article or tag modification operations depend on that category
After configuration, the framework will automatically record all data changes (create, update, delete) for this table. You can view and rollback these operations in the operation log page.
Done! Now you have a complete CRUD feature, including list page, search, create, edit, delete, and all other functionality. If operation logging is configured, all data changes will be automatically recorded.
6.3 Custom Feature Extensions
The framework provides many extension points for customizing various features.
6.3.1 Extension 1: Using Batch Operations
If you need batch edit or batch delete, just change g.X to g.XB. The framework will automatically add batch operation buttons and functionality.
6.3.2 Extension 2: Adding Fixed Query Conditions
By configuring AndWheres, you can add fixed query conditions. For example, only show published data, only show current user's data, etc.
6.3.3 Extension 3: Custom Data Processing
Override the WrapData method to perform custom processing before returning data. For example, add calculated fields, format data, etc.
6.3.4 Extension 4: Custom Search Logic
Override the buildCondition method to implement custom search logic. For example, date range search, complex condition combinations, etc.
6.3.5 Extension 5: Custom Save Logic
Override the ActionSave method to perform custom validation and processing before saving. For example, set default values, calculate field values, etc.
6.3.6 Extension 6: Relational Queries
Implement relational queries in WrapData to convert foreign key IDs to related data. For example, display category names and author names in article lists.
6.3.7 Extension 7: Operation Log Management
The framework includes complete operation logging functionality. You can:
View Operation History:
- Access
/base/op/indexto view all operation events - Support searching by data table, user, time, etc.
- Click the details button to view specific change records and field differences
Rollback Operations:
- Select operation events to rollback
- Framework automatically checks operation dependencies
- Confirm to execute rollback, data is restored to the state before changes
- Rollback operations themselves are also recorded, forming a complete audit chain
Customize Display Fields:
- Configure fields to display in the
showfield ofop.json - Framework calculates differences and displays based on these fields
- Supports field translation, automatically converts foreign key IDs to display names
VII. FAQ
For answers to common questions, including custom list pages, adding validation, relational queries, custom search, etc., please refer to the FAQ Documentation.
VIII. License
MIT License
gin-vue-web - Rapid Web Application Development
Made with ❤️ by the gin-vue-web Team
Explore related projects
Loading…