go grpc demo for code

王念
2023-12-01

目录

1 proto

2 server

3 client


1 proto

syntax = "proto3";
// protoc --go_out=. --go-grpc_out=. user.proto
package user;

option go_package = "./user";

message UserInfoRequest {
  int64 id = 1;
}

message UserInfoResponse {
  int64 id = 1;
  string name = 2;
  int32 age =3;
}

service UserService {
  rpc getUserInfo(UserInfoRequest) returns (UserInfoResponse) {};
}

2 server

func main() {
	l, err := net.Listen("tcp", "0.0.0.0:9999")
	if err != err {
		panic(err)
	}
	fmt.Println("listen on 0.0.0.0:9999")
	grpcServer := grpc.NewServer()
	user.RegisterUserServiceServer(grpcServer, &Server{})
	err = grpcServer.Serve(l)
	if err != nil {
		panic(err)
	}
}

type Server struct {
	user.UnimplementedUserServiceServer
}

func (s Server) GetUserInfo(c context.Context, req *user.UserInfoRequest) (*user.UserInfoResponse, error) {
	return &user.UserInfoResponse{
		Id:   req.Id,
		Name: "congratulations",
		Age:  100,
	}, nil
}

3 client

func main() {
	conn, err := grpc.Dial("127.0.0.1:9999", grpc.WithInsecure())
	if err != nil {
		panic(err)
	}
	defer conn.Close()
	client := user.NewUserServiceClient(conn)
	req := &user.UserInfoRequest{
		Id: 1,
	}
	response, err := client.GetUserInfo(context.Background(), req)
	if err != nil {
		panic(err)
	}
	fmt.Println("success:", response)
}

 类似资料:

相关阅读

相关文章

相关问答