在 golang GRPC 服务器中处理 REST 请求

问题描述

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

我发现 grpc-gateway 可以将现有的原型架构转换为休息端点,但我认为这不适合我的需求。

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

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

解决方法

看起来我在付出足够大的努力来解决我自己的问题之前问了我的问题。这是在 GRPC 请求旁边提供 REST 请求的示例

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")
}

根据上述情况,向 POST 发送 localhost:6789/event 将导致发出 handling 日志行。