proto 声明SayHi
先删除go.mod 从新初始化一下
go mod init xgs_kratos
go mod tidy
编辑 api/helloword/v1/greeter.proto 新声明一个方法
rpc SayHi (HelloHiRequest) returns (HelloHiReply) {
option (google.api.http) = {
post: "/hi"
body: "*"
};
}
post请求的话 body必须写,定义好之后
#执行
make api
#在执行
make generate
编辑service层
Go
package service
import (
"context"
v1 "xgs_kratos/api/helloworld/v1"
"xgs_kratos/internal/biz"
)
// GreeterService is a greeter service.
type GreeterService struct {
v1.UnimplementedGreeterServer
uc *biz.GreeterUsecase
}
// NewGreeterService new a greeter service.
func NewGreeterService(uc *biz.GreeterUsecase) *GreeterService {
return &GreeterService{uc: uc}
}
// SayHello implements helloworld.GreeterServer.
func (s *GreeterService) SayHello(ctx context.Context, in *v1.HelloRequest) (*v1.HelloReply, error) {
g, err := s.uc.CreateGreeter(ctx, &biz.Greeter{Hello: in.Name})
if err != nil {
return nil, err
}
return &v1.HelloReply{Message: "Hello " + g.Hello}, nil
}
// SayHi implements helloworld.GreeterServer.
func (s *GreeterService) SayHi(ctx context.Context, in *v1.HelloHiRequest) (*v1.HelloHiReply, error) {
g, err := s.uc.CreateGreeter(ctx, &biz.Greeter{Hello: in.Name})
if err != nil {
return nil, err
}
return &v1.HelloHiReply{Message: "Hello " + g.Hello}, nil
}
运行 kratos run
postman请求的结果如下