Skip to content

Instantly share code, notes, and snippets.

@cdfmlr
Last active September 19, 2020 12:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cdfmlr/95186d2db5e3c510b324e6ad47a76c9b to your computer and use it in GitHub Desktop.
Save cdfmlr/95186d2db5e3c510b324e6ad47a76c9b to your computer and use it in GitHub Desktop.
[Intro] Use gRPC in Golang

[Intro] Use gRPC in Golang

一个处理用户信息的 RPC 实例。客户端通过给定用户名,从服务端查询用户信息。

项目结构如下:

grpc
├── client
│   └── main.go
├── go.mod
├── go.sum
├── proto
│   ├── user.pb.go
│   ├── user.proto
│   └── user_grpc.pb.go
└── server
    └── main.go
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
"grpc.learn/proto"
)
func main() {
// 连接服务
address := "localhost:8080"
cc, err := grpc.Dial(address, grpc.WithInsecure())
if err != nil {
fmt.Println("Dial error:", err)
}
defer cc.Close()
// 实例化 gRPC 客户端
client := proto.NewUserInfoClient(cc)
// 调用服务
req := &proto.UserRequest{Name: "foo"}
resp, err := client.GetUserInfo(context.Background(), req)
if err != nil {
fmt.Println("GetUserInfo error:", err)
}
fmt.Printf("resp: %#v", resp)
}
module grpc.learn
go 1.12
require (
github.com/golang/protobuf v1.4.0
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3 // indirect
golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135 // indirect
google.golang.org/grpc v1.32.0
google.golang.org/grpc/cmd/protoc-gen-go-grpc v0.0.0-20200917190803-0f7e218c2cf4 // indirect
google.golang.org/protobuf v1.23.0
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc // indirect
)
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.25.0
// protoc v3.13.0
// source: user.proto
package proto
import (
proto "github.com/golang/protobuf/proto"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
// This is a compile-time assertion that a sufficiently up-to-date version
// of the legacy proto package is being used.
const _ = proto.ProtoPackageIsVersion4
// 用户信息请求参数
type UserRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
}
func (x *UserRequest) Reset() {
*x = UserRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_user_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *UserRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*UserRequest) ProtoMessage() {}
func (x *UserRequest) ProtoReflect() protoreflect.Message {
mi := &file_user_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use UserRequest.ProtoReflect.Descriptor instead.
func (*UserRequest) Descriptor() ([]byte, []int) {
return file_user_proto_rawDescGZIP(), []int{0}
}
func (x *UserRequest) GetName() string {
if x != nil {
return x.Name
}
return ""
}
// 用户信息请求响应
type UserResponse struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Id int32 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"`
Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"`
Age int32 `protobuf:"varint,3,opt,name=age,proto3" json:"age,omitempty"`
Hobby []string `protobuf:"bytes,4,rep,name=hobby,proto3" json:"hobby,omitempty"`
}
func (x *UserResponse) Reset() {
*x = UserResponse{}
if protoimpl.UnsafeEnabled {
mi := &file_user_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *UserResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*UserResponse) ProtoMessage() {}
func (x *UserResponse) ProtoReflect() protoreflect.Message {
mi := &file_user_proto_msgTypes[1]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use UserResponse.ProtoReflect.Descriptor instead.
func (*UserResponse) Descriptor() ([]byte, []int) {
return file_user_proto_rawDescGZIP(), []int{1}
}
func (x *UserResponse) GetId() int32 {
if x != nil {
return x.Id
}
return 0
}
func (x *UserResponse) GetName() string {
if x != nil {
return x.Name
}
return ""
}
func (x *UserResponse) GetAge() int32 {
if x != nil {
return x.Age
}
return 0
}
func (x *UserResponse) GetHobby() []string {
if x != nil {
return x.Hobby
}
return nil
}
var File_user_proto protoreflect.FileDescriptor
var file_user_proto_rawDesc = []byte{
0x0a, 0x0a, 0x75, 0x73, 0x65, 0x72, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x05, 0x70, 0x72,
0x6f, 0x74, 0x6f, 0x22, 0x21, 0x0a, 0x0b, 0x55, 0x73, 0x65, 0x72, 0x52, 0x65, 0x71, 0x75, 0x65,
0x73, 0x74, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09,
0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x22, 0x5a, 0x0a, 0x0c, 0x55, 0x73, 0x65, 0x72, 0x52, 0x65,
0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01,
0x28, 0x05, 0x52, 0x02, 0x69, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02,
0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x10, 0x0a, 0x03, 0x61, 0x67,
0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x05, 0x52, 0x03, 0x61, 0x67, 0x65, 0x12, 0x14, 0x0a, 0x05,
0x68, 0x6f, 0x62, 0x62, 0x79, 0x18, 0x04, 0x20, 0x03, 0x28, 0x09, 0x52, 0x05, 0x68, 0x6f, 0x62,
0x62, 0x79, 0x32, 0x44, 0x0a, 0x08, 0x55, 0x73, 0x65, 0x72, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x38,
0x0a, 0x0b, 0x47, 0x65, 0x74, 0x55, 0x73, 0x65, 0x72, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x12, 0x2e,
0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x55, 0x73, 0x65, 0x72, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73,
0x74, 0x1a, 0x13, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x55, 0x73, 0x65, 0x72, 0x52, 0x65,
0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
file_user_proto_rawDescOnce sync.Once
file_user_proto_rawDescData = file_user_proto_rawDesc
)
func file_user_proto_rawDescGZIP() []byte {
file_user_proto_rawDescOnce.Do(func() {
file_user_proto_rawDescData = protoimpl.X.CompressGZIP(file_user_proto_rawDescData)
})
return file_user_proto_rawDescData
}
var file_user_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_user_proto_goTypes = []interface{}{
(*UserRequest)(nil), // 0: proto.UserRequest
(*UserResponse)(nil), // 1: proto.UserResponse
}
var file_user_proto_depIdxs = []int32{
0, // 0: proto.UserInfo.GetUserInfo:input_type -> proto.UserRequest
1, // 1: proto.UserInfo.GetUserInfo:output_type -> proto.UserResponse
1, // [1:2] is the sub-list for method output_type
0, // [0:1] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_user_proto_init() }
func file_user_proto_init() {
if File_user_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_user_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*UserRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_user_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*UserResponse); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_user_proto_rawDesc,
NumEnums: 0,
NumMessages: 2,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_user_proto_goTypes,
DependencyIndexes: file_user_proto_depIdxs,
MessageInfos: file_user_proto_msgTypes,
}.Build()
File_user_proto = out.File
file_user_proto_rawDesc = nil
file_user_proto_goTypes = nil
file_user_proto_depIdxs = nil
}
syntax = "proto3";
package proto;
// 用户信息请求参数
message UserRequest {
string name = 1;
}
// 用户信息请求响应
message UserResponse {
int32 id = 1;
string name = 2;
int32 age = 3;
repeated string hobby = 4;
}
// 用户信息接口
service UserInfo {
// 获取用户信息,请求参数为 UserRequest,返回响应为 UserResponse
rpc GetUserInfo (UserRequest) returns (UserResponse) {}
}
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
package proto
import (
context "context"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
)
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion7
// UserInfoClient is the client API for UserInfo service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
type UserInfoClient interface {
// 获取用户信息,请求参数为 UserRequest,返回响应为 UserResponse
GetUserInfo(ctx context.Context, in *UserRequest, opts ...grpc.CallOption) (*UserResponse, error)
}
type userInfoClient struct {
cc grpc.ClientConnInterface
}
func NewUserInfoClient(cc grpc.ClientConnInterface) UserInfoClient {
return &userInfoClient{cc}
}
var userInfoGetUserInfoStreamDesc = &grpc.StreamDesc{
StreamName: "GetUserInfo",
}
func (c *userInfoClient) GetUserInfo(ctx context.Context, in *UserRequest, opts ...grpc.CallOption) (*UserResponse, error) {
out := new(UserResponse)
err := c.cc.Invoke(ctx, "/proto.UserInfo/GetUserInfo", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// UserInfoService is the service API for UserInfo service.
// Fields should be assigned to their respective handler implementations only before
// RegisterUserInfoService is called. Any unassigned fields will result in the
// handler for that method returning an Unimplemented error.
type UserInfoService struct {
// 获取用户信息,请求参数为 UserRequest,返回响应为 UserResponse
GetUserInfo func(context.Context, *UserRequest) (*UserResponse, error)
}
func (s *UserInfoService) getUserInfo(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(UserRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return s.GetUserInfo(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: s,
FullMethod: "/proto.UserInfo/GetUserInfo",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return s.GetUserInfo(ctx, req.(*UserRequest))
}
return interceptor(ctx, in, info, handler)
}
// RegisterUserInfoService registers a service implementation with a gRPC server.
func RegisterUserInfoService(s grpc.ServiceRegistrar, srv *UserInfoService) {
srvCopy := *srv
if srvCopy.GetUserInfo == nil {
srvCopy.GetUserInfo = func(context.Context, *UserRequest) (*UserResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method GetUserInfo not implemented")
}
}
sd := grpc.ServiceDesc{
ServiceName: "proto.UserInfo",
Methods: []grpc.MethodDesc{
{
MethodName: "GetUserInfo",
Handler: srvCopy.getUserInfo,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "user.proto",
}
s.RegisterService(&sd, nil)
}
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
"grpc.learn/proto"
"net"
)
// userInfoService 是 proto.UserInfoService 的实例,即 protobuf 中定义的 service UserInfoService 实例
// 需要实现 GetUserInfo 方法
var userInfoService = proto.UserInfoService{
GetUserInfo: getUserInfo,
}
// getUserInfo 是获取用户信息的具体处理
// 请求参数为 UserRequest,返回响应为 UserResponse
func getUserInfo(ctx context.Context, request *proto.UserRequest) (response *proto.UserResponse, err error) {
name := request.Name
fmt.Println("GetUserInfo: name =", name)
// Fake query
if name == "foo" {
response = &proto.UserResponse{
Id: 1,
Name: "foo",
Age: 12,
Hobby: []string{"eating", "sleep"},
}
return response, nil
}
return response, fmt.Errorf("unknown user: name=%s", name)
}
func main() {
// 实例化 gRPC,注册服务
s := grpc.NewServer()
proto.RegisterUserInfoService(s, &userInfoService)
// 监听网络
address := "localhost:8080"
listener, err := net.Listen("tcp", address)
if err != nil {
panic(err)
}
fmt.Println("Listening tcp:", address)
// 启动 gRPC 服务
err = s.Serve(listener)
if err != nil {
panic(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment