【问题标题】:Handle REST requests in golang GRPC server在 golang GRPC 服务器中处理 REST 请求
【发布时间】:2021-06-30 01:36:21
【问题描述】:

用 golang 编写的 GRPC 服务器是否也可以处理 REST 请求?

我找到了grpc-gateway,它可以将现有的原型模式转换为休息端点,但我认为这不适合我的需求。

我已经编写了一个 GRPC 服务器,但我还需要为来自外部服务(如 Github 或 Stripe)的 webhook 请求提供服务。我正在考虑编写第二个基于 REST 的服务器来接受这些 webhook(并可能将它们翻译/转发到 GRPC 服务器),但这似乎有点代码味道。

理想情况下,我希望我的 GRPC 服务器也能够处理 REST 请求,例如 /webhook/event 等端点,但我不确定这是否可能以及是否可行配置它。

【问题讨论】:

标签: rest go grpc grpc-go


【解决方案1】:

看起来我在付出足够大的努力自己解决之前就问了我的问题。这是一个将 REST 请求与 GRPC 请求一起提供服务的示例

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

    // here we register and HTTP server listening on port 6789
    // note that we do this in with gofunc so that the rest of this main function can execute - this probably isn't ideal
    http.HandleFunc("/event", Handle)
    go http.Serve(lis, nil)

    // now we set up GRPC
    grpcServer := grpc.NewServer()

    // this is a GRPC service defined in a proto file and then generated with protoc
    pipelineServer := Server{}

    pipeline.RegisterPipelinesServer(grpcServer, pipelineServer)


    if err := grpcServer.Serve(lis); err != nil {
        log.Fatalf("failed to serve: %s", err)
    }
}

func Handle(response http.ResponseWriter, request *http.Request) {
    log.Infof("handling")
}

通过上述方式,向localhost:6789/event 发送POST 将导致发出handling 日志行。

【讨论】:

  • 啊,但是这两个服务器的正常关闭似乎是不可能的,因为 http 服务器和 grpc 服务器的关闭过程都关闭了侦听器。这会导致第二个关闭服务器失败,因为侦听器过早关闭。
猜你喜欢
  • 2018-01-09
  • 1970-01-01
  • 2017-05-28
  • 2020-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-25
  • 2016-01-03
  • 2021-03-25
相关资源
最近更新 更多