目录
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) {};
}
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
}
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)
}