Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $YECBGYFECGEAFWHA as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2

Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $BBWFDDBHHYHDXXAB as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2
如何在Golang中使用gRPC网关转换REST请求_创想鸟

如何在Golang中使用gRPC网关转换REST请求

答案:在Golang中通过gRPC网关将REST转为gRPC调用需定义带google.api.http注解的proto文件,生成gRPC和服务代码后分别启动gRPC服务器和HTTP网关,实现RESTful API到内部gRPC的自动转换。

如何在golang中使用grpc网关转换rest请求

在Golang中使用gRPC网关将REST请求转换为gRPC调用,是构建现代微服务API的常见做法。它允许你通过HTTP/JSON对外提供RESTful接口,同时内部使用高性能的gRPC进行服务间通信。整个流程依赖于Protocol Buffers定义服务,并借助grpc-gateway生成反向代理代码。

定义Protocol Buffer服务

要启用gRPC网关,首先需要在.proto文件中定义gRPC服务,并添加特定的google.api.http注解来映射REST路径。

安装必要的proto插件:

go install github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-grpc-gateway@latest
go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest

编写service.proto文件:

立即学习“go语言免费学习笔记(深入)”;

syntax = “proto3”;

package example;

import “google/api/annotations.proto”;

message HelloRequest {
  string name = 1;
}

message HelloResponse {
  string message = 1;
}

service Greeter {
  rpc SayHello (HelloRequest) returns (HelloResponse) {
    option (google.api.http) = {
      get: “/v1/hello/{name}”
    };
  }
}

这里option (google.api.http)将SayHello方法绑定到GET /v1/hello/{name},URL中的{name}会自动映射到请求字段。

生成gRPC和gRPC-Gateway代码

运行protoc命令生成Go代码:

protoc
  –go_out=. –go_opt=paths=source_relative
  –go-grpc_out=. –go-grpc_opt=paths=source_relative
  –grpc-gateway_out=. –grpc-gateway_opt=paths=source_relative
  service.proto

这会生成三个文件:

service.pb.go:基础结构体和gRPC客户端/服务接口service_grpc.pb.go:gRPC服务实现桩代码service.pb.gw.go:gRPC网关的HTTP处理器,负责将REST转为gRPC调用

启动gRPC服务与HTTP网关

你需要同时运行gRPC服务器和HTTP网关。通常gRPC监听本地端口,而HTTP网关作为前端代理转发请求。

实现gRPC服务:

type server struct{}

func (s *server) SayHello(ctx context.Context, req *example.HelloRequest) (*example.HelloResponse, error) {
  return &example.HelloResponse{Message: “Hello ” + req.Name}, nil
}

启动gRPC服务器:

lis, _ := net.Listen(“tcp”, “:50051”)
s := grpc.NewServer()
example.RegisterGreeterServer(s, &server{})
s.Serve(lis)

启动HTTP网关(反向代理):

ctx := context.Background()
mux := runtime.NewServeMux()
opts := []grpc.DialOption{grpc.WithInsecure()}
_ = example.RegisterGreeterHandlerFromEndpoint(ctx, mux, “localhost:50051”, opts)

http.ListenAndServe(“:8080”, mux)

现在你可以通过GET /v1/hello/world访问服务,网关会将其转换为gRPC调用并返回JSON响应。

处理复杂路由和方法

除了GET,你还可以映射POST、PUT等方法,并指定body字段:

rpc CreateBook(CreateBookRequest) returns (CreateBookResponse) {
  option (google.api.http) = {
    post: “/v1/shelves/{shelf_id}/books”
    body: “book”
  };
}

这表示POST数据到/v1/shelves/123/books,请求体中的JSON会被解析到book字段。

确保你的proto文件导入google/api/annotations.proto和google/api/http.proto,可通过buf或手动下载管理依赖。

基本上就这些。只要定义好proto注解,生成代码并正确启动两个服务,gRPC网关就能自动完成REST到gRPC的转换,无需手动写HTTP handler。这种方式统一了API契约,便于维护和文档生成。不复杂但容易忽略的是注解语法和生成命令的参数顺序。

以上就是如何在Golang中使用gRPC网关转换REST请求的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1419967.html

赞 (0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
Go语言中的“死代码”:编译器行为与静态分析
上一篇 2025年12月16日 13:37:59
如何在Golang中实现简单的API版本管理_Golang API版本管理项目实战汇总
下一篇 2025年12月16日 13:38:04

相关推荐

发表回复

登录后才能评论
关注微信