dongmeng9048 2019-04-22 21:25
浏览 107
已采纳

如何在Go中创建通用GRPC服务器启动功能

I'm trying to abstract the start of a GRPC server

The original main function is the following:

func main() {
    lis, err := net.Listen("tcp", port)
    if err != nil {
        log.Fatalf("failed to listen: %v", err)
    }

    s := grpc.NewServer()
    pb.RegisterCollectionServer(s, &server.Server{})
    // Register reflection service on gRPC server.
    reflection.Register(s)
    if err := s.Serve(lis); err != nil {
        log.Fatalf("failed to serve: %v", err)
    }
}

My goal is to have something like this:

func startService(sr func(*grpc.Server, interface{}), srv interface{}) error {
    lis, err := net.Listen("tcp", port)
    if err != nil {
        return err
    }
    s := grpc.NewServer()
    sr(s, srv)
    reflection.Register(s)
    return s.Serve(lis)
}

func main() {
    err := startService(pb.RegisterCollectionServer, &server.Server{})

    if err != nil {
        log.Fatalf("failed to start Service: %v", err)
    }
}

But this gives me the following error:

cannot use collection_api.RegisterCollectionServer (type func(*grpc.Server, collection_api.CollectionServer)) as type func(*grpc.Server, interface {}) in argument to startServicego

It seems that collection_api.CollectionServer is not a valid interface{} type.

Any idea how to make this work?

  • 写回答

1条回答 默认 最新

  • doraemon0769 2019-04-23 11:00
    关注

    In your setup the function signature of collector_api.RegisterCollectionServer must match exactly func(*grpc.Server, interface{}), there is no "is-kind-of" in Go as there is in other languages.

    If you want to keep the startService function independent of the collection_api types, you can use a anonymous function in main(). If you know that you what ever you are registering is always dependent on the implementation of the anonymous function (in this case &server.Server{}), then you can leave this detail out of the function signature of startService and put it into the anonymous function:

    func startService(sr func(*grpc.Server)) error {
        lis, err := net.Listen("tcp", port)
        if err != nil {
            return err
        }
        s := grpc.NewServer()
        sr(s)
        reflection.Register(s)
        return s.Serve(lis)
    }
    
    func main() {
        err := startService(func(grpcServer *grpc.Server) {
                pb.RegisterCollectionServer(grpcServer, &server.Server{})
            }, &server.Server{})
    
        if err != nil {
            log.Fatalf("failed to start Service: %v", err)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题