Skip to main content
Version: 2.10.x(Latest)

User gRPC Service Practice

Github Source: https://github.com/gogf/examples/tree/main/practices/user-grpc-service

Description

This example demonstrates a complete user management microservice using gRPC and GoFrame. It showcases:

  • Full CRUD operations for user management
  • gRPC service implementation with Protocol Buffers
  • MySQL database integration with DAO pattern
  • Servicelayer business logic
  • Auto-generated code from database schema
  • Production-ready project structure

Structure

.
├── api/ # API definitions
│ ├── pbentity/ # Auto-generated protobuf entities
│ └── user/ # User service API
│ └── v1/ # API version 1
├── hack/ # Development tools
│ └── config.yaml # CLI tool configuration
├── internal/ # Internal packages
│ ├── cmd/ # Command definitions
│ ├── consts/ # Constants
│ ├── controller/ # gRPC controllers
│ │ └── user/ # User controller(auto-generated + 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
├── manifest/ # Deployment manifests
│ ├── config/ # Configuration files
│ │ └── config.yaml # Application config
│ ├── deploy/ # Deployment files
│ ├── docker/ # Docker files
│ ├── protobuf/ # Protocol buffer definitions
│ │ ├── pbentity/ # Entity definitions
│ │ └── user/ # User service definitions
│ └── sql/ # SQL scripts
│ └── create.sql # Database schema
├── main.go # Application entry point
├── go.mod # Go module file
└── Makefile # Build automation

Features

The example showcases the following features:

Service Implementation

  • gRPC server with Protocol Buffers
  • User CRUD operations (Create, GetOne, GetList, Delete)
  • Request validation
  • Error handling
  • Context management

Database Integration

  • MySQL database connection
  • DAO pattern for data access
  • Auto-generated DAO, DO, and Entity code
  • Transaction support
  • Query builder

Project Organization

  • Standard GoFrame project structure
  • Separation of concerns (Controller, Service, DAO)
  • Configuration management
  • Logging support
  • Build automation with Makefile

Requirements

Prerequisites

Install GoFrame CLI Tool

go install github.com/gogf/gf/cmd/gf/v2@latest

Or use Makefile:

make cli

Setup 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.0

Initialize 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.sql

Or 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: true

Usage

Generate Code

Generate DAO, DO, and Entity code from database:

make dao

Generate Protocol Buffer Go files:

make pb

Generate Protocol Buffer entity files from database:

make pbentity

Run the Server

Start the gRPC server:

go run main.go

The 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:

  1. Install grpcurl:

    brew install grpcurl
  2. List available services:

    grpcurl -plaintext localhost:8000 list
  3. Create a user:

    grpcurl -plaintext -d '{"Passport":"user001","Password":"123456","Nickname":"Test User"}' \
    localhost:8000 user.User/Create
  4. Get user by ID:

    grpcurl -plaintext -d '{"Id":1}' \
    localhost:8000 user.User/GetOne
  5. Get user list:

    grpcurl -plaintext -d '{"Page":1,"Size":10}' \
    localhost:8000 user.User/GetList
  6. Delete 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 gRPC requests
  • Validates request parameters
  • Calls Service layer 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 Service files
make service

# Generate Protocol Buffer files
make pb

# Generate Protocol Buffer Entity files
make pbentity

Build Docker Image

make image

Deploy to Kubernetes

make deploy

Notes

  • Ensure MySQL is running before starting the application
  • Default database credentials are root:12345678 (change in production)
  • The service uses port 8000 by default
  • Protocol buffer files are in manifest/protobuf
  • SQL schema is in manifest/sql/create.sql