Golang gRPC 和 gRPC-gateway 结合使用
一、安装
go get -u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway go get -u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger go get -u github.com/golang/protobuf/protoc-gen-go
二、proto 文件

syntax = "proto3"; package gateway; import "google/api/annotations.proto"; message StringMessage { string value = 1; } service Gateway { rpc Echo(StringMessage) returns (StringMessage) { option (google.api.http) = { post: "/v1/example/echo" body: "*" }; } }
执行 protoc 编译,生成两个 go 文件,一个是提供 service 的,一个是 gateway 的:
protoc --proto_path=../ -I/usr/local/include -I. -I/home/go-plugin/src -I/home/go-plugin/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis --go_out=plugins=grpc:. gateway.proto
protoc --proto_path=../ -I/usr/local/include -I. -I/home/go-plugin/src -I/home/go-plugin/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis --grpc-gateway_out=logtostderr=true:. gateway.proto
生成的文件如下:
第一个是 service,第二个是 gateway
三、编写 go 程序
1、service

package main import ( "log" "net" pb "test_grpc/gateway" "google.golang.org/grpc" "golang.org/x/net/context" ) const ( PORT = ":9192" ) type server struct {} func (s *server) Echo(ctx context.Context, in *pb.StringMessage) (*pb.StringMessage, error) { log.Println("request: ", in.Value) return &pb.StringMessage{Value: "Hello " + in.Value}, nil } func main() { lis, err := net.Listen("tcp", PORT) if err != nil { log.Fatalf("failed to listen: %v", err) } s := grpc.NewServer() pb.RegisterGatewayServer(s, &server{}) log.Println("rpc服务已经开启") s.Serve(lis) }
2、gateway

package main import ( "flag" "net/http" "log" "github.com/golang/glog" "golang.org/x/net/context" "github.com/grpc-ecosystem/grpc-gateway/runtime" "google.golang.org/grpc" gw "test_grpc/gateway" ) var ( echoEndpoint = flag.String("echo_endpoint", "localhost:9192", "endpoint of Gateway") ) func run() error { ctx := context.Background() ctx, cancel := context.WithCancel(ctx) defer cancel() mux := runtime.NewServeMux() opts := []grpc.DialOption{grpc.WithInsecure()} err := gw.RegisterGatewayHandlerFromEndpoint(ctx, mux, *echoEndpoint, opts) if err != nil { return err } log.Println("服务开启") return http.ListenAndServe(":8080", mux) } func main() { flag.Parse() defer glog.Flush() if err := run(); err != nil { glog.Fatal(err) } }
四、开启服务
先开启 service,再开启 gateway
you are the best!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· 单线程的Redis速度为什么快?
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
2015-12-21 Nginx + Apache 反向代理
2015-12-21 Ubuntu Nginx安装
2015-12-21 Nginx配置文件详解