gRPC
- Context Usage
Code Source: https://github.com/gogf/examples/tree/main/grpc/ctx
Description
This example demonstrates how to use context and metadata in gRPC
with GoFrame
. It shows how to:
- Pass metadata through
gRPC
context - Handle context values and deadlines
- Manage request context
- Process context metadata
Structure
.
├── client/ # Client example
│ └── client.go # Client implementation with context
├── controller/ # Service controllers
│ └── helloworld.go # Hello service with context handling
├── protobuf/ # Protocol buffer definitions
├── server/ # Server example
│ ├── config.yaml # Server configuration
│ └── server.go # Server implementation
├── go.mod # Go module file
└── go.sum # Go module checksums
Features
The example showcases the following features:
-
Context Management
- Metadata handling
- Value propagation
- Deadline management
- Cancellation handling
-
Client Usage
- Context creation
- Metadata attachment
- Context values
- Timeout configuration
-
Server Features
- Context extraction
- Metadata processing
- Value retrieval
- Timeout handling
Requirements
Prerequisites
- Protocol buffer compiler installed:
# For macOS
brew install protobuf
# Install protoc-gen-go and protoc-gen-go-grpc
go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
Usage
-
Generate protocol buffer code:
cd protobuf
protoc --go_out=paths=source_relative:. --go-grpc_out=paths=source_relative:. *.proto -
Start the server:
cd server
go run server.go -
Run the client:
cd client
go run client.go
Implementation Details
The example demonstrates:
- Context propagation in
gRPC
- Metadata handling with
GoFrame