server.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package server
  2. import (
  3. "context"
  4. "errors"
  5. "github.com/go-kit/kit/endpoint"
  6. transport"github.com/go-kit/kit/transport/grpc"
  7. "standard/etcd/go-kit/pb"
  8. )
  9. type BookServer struct {
  10. BookListHandler transport.Handler
  11. BookInfoHandler transport.Handler
  12. }
  13. //通过grpc调用GetBookInfo时,GetBookInfo只做数据透传, 调用BookServer中对应Handler.ServeGRPC转交给go-kit处理
  14. func (s *BookServer) GetBookInfo(ctx context.Context, in *pb.Request) (*pb.Book, error) {
  15. //ServeGRPC转交给go-kit处理
  16. _, rsp, err := s.BookInfoHandler.ServeGRPC(ctx, in)
  17. if err != nil {
  18. return nil, err
  19. }
  20. if _,ok:=rsp.(*pb.BookInfo);!ok {
  21. return nil,errors.New("rsp.(*book.BookInfo)断言出错")
  22. }
  23. return rsp.(*pb.Book), err //直接返回断言的结果
  24. }
  25. func (s *BookServer) GetBookList(ctx context.Context, in *pb.Request) (*pb.BookList, error) {
  26. _, rsp, err := s.BookListHandler.ServeGRPC(ctx, in)
  27. if err != nil {
  28. return nil, err
  29. }
  30. return rsp.(*pb.BookList), err
  31. }
  32. //endpoint
  33. //定义 Request、Response 格式
  34. //创建关于业务的构造函数
  35. func MakeGetBookInfoEndpoint() endpoint.Endpoint {
  36. return func(ctx context.Context, request interface{}) (interface{}, error) {
  37. //请求详情时返回 书籍信息
  38. req := request.(*pb.Request)
  39. b := new(pb.BookInfo)
  40. b.Book.Id= req.Par
  41. return b, nil
  42. }
  43. }
  44. func MakeGetBookListEndpoint()endpoint.Endpoint {
  45. return func(ctx context.Context, request interface{}) (response interface{}, err error) {
  46. b:=new(pb.BookList)
  47. b.Books=append(b.Books,&pb.Book{Id:"1",Name:"Go语言入门到精通"})
  48. b.Books=append(b.Books,&pb.Book{Id:"2",Name:"微服务入门到精通"})
  49. b.Books=append(b.Books,&pb.Book{Id:"3",Name:"区块链入门到精通"})
  50. return b,nil
  51. }
  52. }
  53. func DecodeRequest(_ context.Context, req interface{}) (interface{}, error) {
  54. return req, nil
  55. }
  56. func EncodeResponse(_ context.Context, rsp interface{}) (interface{}, error) {
  57. return rsp, nil
  58. }