rpc

package
v1.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 9, 2026 License: MIT Imports: 8 Imported by: 0

README

RPC

rpc 包提供了标准化的 RPC 调用封装与响应处理工具。

设计理念

本包旨在统一处理微服务间的响应格式,遵循 Code/Message/Data 模式:

  • Code:业务状态码(200 表示成功)。
  • Message:业务提示信息。
  • Data:实际业务数据。

核心功能

WithRemoteInvoke

泛型函数,用于发起远程调用并自动处理响应解包。

处理逻辑

  1. 网络错误:直接返回 error
  2. Nil 检查:防御性处理“带类型的 nil”。
  3. 业务错误:若 Code != 200,提取 Message 并封装为 error 返回。
  4. 成功:仅返回 Data 部分。

使用示例

假设 Proto 定义如下:

message GetUserResponse {
    uint32 code = 1;
    string message = 2;
    User data = 3;
}

调用代码:

import "github.com/fireflycore/go-micro/rpc"

// T:业务数据类型(pb.User)
// R:响应类型(*pb.GetUserResponse),需实现 rpc.RemoteResponse[pb.User]
user, err := rpc.WithRemoteInvoke[pb.User, *pb.GetUserResponse](func() (*pb.GetUserResponse, error) {
	return client.GetUser(ctx, &pb.GetUserRequest{Id: 1})
})

if err != nil {
	// 处理网络错误或业务错误(Code != 200)
	return err
}

// 直接使用 user 对象
fmt.Println(user.Name)

Documentation

Overview

Package rpc 提供标准化的 RPC 调用封装与响应处理工具。

Index

Constants

View Source
const MetaKeyParseErrorFormat = "%s 解析失败"

MetaKeyParseErrorFormat 用于构造元信息缺失/解析失败的错误文本。

Variables

View Source
var (
	// ErrRemoteResponseIsNil 表示远程调用返回的响应对象为空。
	ErrRemoteResponseIsNil = errors.New("远程响应为空")
	// ErrRemoteCallFailed 表示远程调用失败但未返回可读错误信息。
	ErrRemoteCallFailed = errors.New("远程调用失败")
)

Functions

func NewRemoteInvokeServiceContext added in v0.9.7

func NewRemoteInvokeServiceContext(bootstrapConf conf.BootstrapConf) context.Context

NewRemoteInvokeServiceContext 初始化远程调用服务上下文, 适用于服务自身(无其他用户特征)调用其他服务时,可基于此上下文进行设置上下文

func NewRemoteServiceGrpcClient added in v0.9.8

func NewRemoteServiceGrpcClient(bootstrapConf conf.BootstrapConf) (*grpc.ClientConn, error)

func ParseMetaKey

func ParseMetaKey(md metadata.MD, key string) (string, error)

ParseMetaKey 解析元信息 key。

func SetRemoteInvokeServiceContext added in v1.0.9

func SetRemoteInvokeServiceContext(ctx context.Context, bootstrapConf conf.BootstrapConf) context.Context

SetRemoteInvokeServiceContext 设置远程调用上下文,基于当前上下文进行设置服务自身的信息,并设置链路追踪,一般是将其封装成中间件使用

Types

type UserContextMeta

type UserContextMeta struct {
	Session  string `json:"session"`
	ClientIp string `json:"client_ip"`

	UserId   string `json:"user_id"`
	AppId    string `json:"app_id"`
	TenantId string `json:"tenant_id"`

	RoleIds []string `json:"role_ids"`
	OrgIds  []string `json:"org_ids"`
}

UserContextMeta 表示用户元信息

func ParseUserContextMeta

func ParseUserContextMeta(md metadata.MD) (raw *UserContextMeta, err error)

ParseUserContextMeta 解析用户上下文元信息。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL