User gRPC Service Practice
Description
This example demonstrates a complete user management microservice using gRPC and GoFrame. It showcases:
- Full
CRUDoperations for user management gRPCservice implementation withProtocol BuffersMySQLdatabase integration withDAOpatternServicelayer business logic- Auto-generated code from database schema
- Production-ready project structure
Structure
.
├── api/ # API definitions(auto-generated by "gf gen pb" from "manifest/protobuf" files)
│ ├── pbentity/ # Auto-generated protobuf entities go files
│ └── user/ # Auto-generated user service API go files
│ └── v1/ # Auto-generated API version v1 go files
├── hack/ # Development tools
│ └── config.yaml # CLI tool configuration
├── internal/ # Internal packages
│ ├── cmd/ # Command definitions
│ ├── consts/ # Global constants
│ ├── controller/ # gRPC controllers implementing the API interfaces
│ │ └── user/ # User controller(auto-generated + custom implementation)
│ ├── dao/ # Data access objects(auto-generated)
│ ├── model/ # Data models
│ │ ├── do/ # Domain objects(auto-generated)
│ │ └── entity/ # Database entities(auto-generated)
│ └── service/ # Business logic
│ └── user/ # User service package
├── manifest/ # Deployment manifests
│ ├── config/ # Configuration files
│ │ └── config.yaml # Application config
│ ├── deploy/ # Deployment files for Kubernetes or other platforms
│ ├── docker/ # Docker files
│ ├── protobuf/ # Protocol buffer definitions
│ │ ├── pbentity/ # Entity definitions(auto-generated from database by "gf gen pbentity")
│ │ └── user/ # User service definitions protobuf files
│ └── sql/ # SQL scripts
│ └── create.sql # Database schema
├── main.go # Application entry point
├── go.mod # Go module file
└── Makefile # Build automationFeatures
The example showcases the following features:
Service Implementation
gRPCserver withProtocol Buffers- User
CRUDoperations (Create,GetOne,GetList,Delete) - Request validation
- Error handling
- Context management
Database Integration
MySQLdatabase connectionDAOpattern for data access- Auto-generated
DAO,DO, andEntitycode - Transaction support
- Query builder
Project Organization
- Standard
GoFrameproject structure - Separation of concerns (Controller, Service, DAO)
- Configuration management
- Logging support
- Build automation with
Makefile
Requirements
- Go
1.23or higher - MySQL
5.7or higher - Protocol Buffers Compiler
Prerequisites
Install GoFrame CLI Tool
go install github.com/gogf/gf/cmd/gf/v2@latestOr use Makefile:
make cliSetup MySQL Database
Run MySQL database using Docker:
docker run -d \
--name mysql-user-service \
-p 3306:3306 \
-e MYSQL_ROOT_PASSWORD=12345678 \
-e MYSQL_DATABASE=test \
mysql:8.0Initialize Database
Execute the SQL script to create the user table:
# Connect to MySQL
docker exec -i mysql-user-service mysql -uroot -p12345678 test < manifest/sql/create.sqlOr manually execute:
CREATE TABLE `user` (
`id` int unsigned NOT NULL AUTO_INCREMENT COMMENT 'User ID',
`passport` varchar(45) NOT NULL COMMENT 'User Passport',
`password` varchar(45) NOT NULL COMMENT 'User Password',
`nickname` varchar(45) NOT NULL COMMENT 'User Nickname',
`create_at` datetime DEFAULT NULL COMMENT 'Created Time',
`update_at` datetime DEFAULT NULL COMMENT 'Updated Time',
`delete_at` datetime DEFAULT NULL COMMENT 'Deleted Time',
PRIMARY KEY (`id`),
UNIQUE KEY `uniq_passport` (`passport`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;Configuration
Update the database configuration in manifest/config/config.yaml:
database:
default:
link: "mysql:root:12345678@tcp(127.0.0.1:3306)/test"
debug: trueUsage
Generate Code
Generate DAO, DO, and Entity code from database:
make daoGenerate Protocol Buffer Go files:
make pbGenerate Protocol Buffer entity files from database:
make pbentityRun the Server
Start the gRPC server:
go run main.goThe server will start on port 8000.
Test the Service
You can test the service using a gRPC client. Here's a simple example using grpcurl:
Install
grpcurl:brew install grpcurlList available services:
grpcurl -plaintext localhost:8000 listCreate a user:
grpcurl -plaintext -d '{"Passport":"user001","Password":"123456","Nickname":"Test User"}' \ localhost:8000 user.User/CreateGet user by ID:
grpcurl -plaintext -d '{"Id":1}' \ localhost:8000 user.User/GetOneGet user list:
grpcurl -plaintext -d '{"Page":1,"Size":10}' \ localhost:8000 user.User/GetListDelete a user:
grpcurl -plaintext -d '{"Id":1}' \ localhost:8000 user.User/Delete
API Reference
User Service
Create
Create a new user.
Request:
message CreateReq {
string Passport = 1; // required
string Password = 2; // required
string Nickname = 3; // required
}Response:
message CreateRes {}GetOne
Get user details by ID.
Request:
message GetOneReq {
uint64 Id = 1; // required
}Response:
message GetOneRes {
pbentity.User User = 1;
}GetList
Get paginated list of users.
Request:
message GetListReq {
int32 Page = 1;
int32 Size = 2;
}Response:
message GetListRes {
repeated pbentity.User Users = 1;
}Delete
Delete a user by ID.
Request:
message DeleteReq {
uint64 Id = 1; // required, min:1
}Response:
message DeleteRes {}Implementation Details
Controller Layer
internal/controller/user/user.go implements the gRPC service interface:
- Handles incoming
gRPCrequests - Validates request parameters
- Calls
Servicelayer for business logic - Returns formatted responses
Service Layer
internal/service/user/user.go contains business logic:
- User retrieval by ID
- User deletion
- Can be extended with more complex business rules
DAO Layer
internal/dao/user.go provides database access:
- Auto-generated from database schema
- Provides type-safe database operations
- Supports chainable query builder
Data Models
- DO (Domain Object): Used for database operations
- Entity: Represents database table structure
- PBEntity: Protocol buffer entity for API responses
Development
Generate All Code
# Generate DAO files
make dao
# Generate Protocol Buffer Entity files to manifest/protobuf/pbentity from database.
make pbentity
# Generate Protocol Buffer files from manifest/protobuf/**.proto files to api/pbentity and api/user go files.
make pbBuild Docker Image
make imageDeploy to Kubernetes
make deployNotes
- Ensure
MySQLis running before starting the application - Default database credentials are
root:12345678(change in production) - The service uses port
8000by default - Protocol buffer files are in
manifest/protobuf - SQL schema is in
manifest/sql/create.sql