---
title: gRPC Service
slug: /examples/practices/user-grpc-service
keywords: [grpc, user, service, crud, mysql, dao, goframe, microservice, protobuf, database, user management, authentication, rest api, backend service, web service, dependency injection, business logic, data access, model, entity]
description: Demonstrates a gRPC-based user management microservice with CRUD operations. Features Protocol Buffers definitions, MySQL integration, DAO pattern data access, and service layer business logic. Ideal for learning GoFrame gRPC microservices and microservice architecture.
hide_title: true
---

# User gRPC Service Practice

## 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
- `Service`layer business logic
- Auto-generated code from database schema
- Production-ready project structure

## Structure

```text
.
├── 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 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

- [Go](https://golang.org/dl/) `1.23` or higher
- [MySQL](https://www.mysql.com/) `5.7` or higher
- [Protocol Buffers Compiler](https://grpc.io/docs/protobuf/)

## Prerequisites

### Install GoFrame CLI Tool

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

Or use `Makefile`:

```bash
make cli
```

### Setup MySQL Database

Run `MySQL` database using `Docker`:

```bash
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:

```bash
# Connect to MySQL
docker exec -i mysql-user-service mysql -uroot -p12345678 test < manifest/sql/create.sql
```

Or manually execute:

```sql
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`:

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

```bash
make dao
```

Generate `Protocol Buffer` Go files:

```bash
make pb
```

Generate `Protocol Buffer` entity files from database:

```bash
make pbentity
```

### Run the Server

Start the `gRPC` server:

```bash
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`:
   ```bash
   brew install grpcurl
   ```

2. List available services:
   ```bash
   grpcurl -plaintext localhost:8000 list
   ```

3. Create a user:
   ```bash
   grpcurl -plaintext -d '{"Passport":"user001","Password":"123456","Nickname":"Test User"}' \
     localhost:8000 user.User/Create
   ```

4. Get user by ID:
   ```bash
   grpcurl -plaintext -d '{"Id":1}' \
     localhost:8000 user.User/GetOne
   ```

5. Get user list:
   ```bash
   grpcurl -plaintext -d '{"Page":1,"Size":10}' \
     localhost:8000 user.User/GetList
   ```

6. Delete a user:
   ```bash
   grpcurl -plaintext -d '{"Id":1}' \
     localhost:8000 user.User/Delete
   ```

## API Reference

### User Service

#### Create

Create a new user.

**Request:**
```protobuf
message CreateReq {
    string Passport = 1; // required
    string Password = 2; // required
    string Nickname = 3; // required
}
```

**Response:**
```protobuf
message CreateRes {}
```

#### GetOne

Get user details by ID.

**Request:**
```protobuf
message GetOneReq {
    uint64 Id = 1; // required
}
```

**Response:**
```protobuf
message GetOneRes {
    pbentity.User User = 1;
}
```

#### GetList

Get paginated list of users.

**Request:**
```protobuf
message GetListReq {
    int32 Page = 1;
    int32 Size = 2;
}
```

**Response:**
```protobuf
message GetListRes {
    repeated pbentity.User Users = 1;
}
```

#### Delete

Delete a user by ID.

**Request:**
```protobuf
message DeleteReq {
    uint64 Id = 1; // required, min:1
}
```

**Response:**
```protobuf
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

```bash
# 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 pb
```

### Build Docker Image

```bash
make image
```

### Deploy to Kubernetes

```bash
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`

