2025-03-02 09:57:02 +08:00

60 lines
1.4 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package hello
import (
"context"
"fmt"
"io"
"github.com/infraboard/mcube/v2/ioc"
grpc_server "github.com/infraboard/mcube/v2/ioc/config/grpc"
"gitlab.com/go-course-project/go17/skills/grpc/service"
"google.golang.org/grpc"
)
func init() {
ioc.Controller().Registry(&HelloServiceServer{})
}
type HelloServiceServer struct {
service.UnimplementedHelloServiceServer
ioc.ObjectImpl
}
func (s *HelloServiceServer) Name() string {
return "hello"
}
func (s *HelloServiceServer) Init() error {
// 需要拿到全局的 grpc server对象, ioc
service.RegisterHelloServiceServer(grpc_server.Get().Server(), &HelloServiceServer{})
return nil
}
func (HelloServiceServer) Hello(ctx context.Context, req *service.HelloRequest) (*service.HelloResponse, error) {
return &service.HelloResponse{
Message: "hello, " + req.MyName,
}, nil
}
func (HelloServiceServer) Chat(stream grpc.BidiStreamingServer[service.ChatRequest, service.ChatResponse]) error {
// 1. 获取用户的请求,然后处理, 处理完成后通过stream 返回给客户端
for {
// 接收一个请求
req, err := stream.Recv()
if err != nil {
// 如果遇到io.EOF表示客户端流被关闭
if err == io.EOF {
return nil
}
return err
}
// 2. 处理请求
fmt.Println(req.Message)
stream.Send(&service.ChatResponse{
Id: req.Id,
IsSuccess: true,
})
}
}