登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-04-10 23:09:33 263浏览 收藏

在Golang实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天golang学习网就整理分享《在 golang GRPC 服务器中处理 REST 请求》,聊聊,希望可以帮助到正在努力赚钱的你。

问题内容

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

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

我已经编写了一个 GRPC 服务器,但我还需要处理来自外部服务(例如 Github 或 Stripe)的 Webhook 请求。我正在考虑编写第二个基于 REST 的服务器来接受这些 webhook(并可能将它们转换/转发到 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 日志行。

理论要掌握,实操不能落!以上关于《在 golang GRPC 服务器中处理 REST 请求》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>