1. 安裝
go install \
github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-grpc-gateway \
github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-openapiv2 \
google.golang.org/protobuf/cmd/protoc-gen-go \
google.golang.org/grpc/cmd/protoc-gen-go-grpc
protocbuf
syntax = "proto3";
package protoc;
import "google/api/annotations.proto";
option go_package ="pb/";
message ProductRequest {
int32 prodId = 1;
}
message ProductResponse {
int32 prod_stock=1;
}
message HelloHTTPRequest {
string name = 1;
}
// HelloResponse 響應結(jié)構(gòu)
message HelloHTTPResponse {
string message = 1;
}
// 定義服務主體
service ProdService{
// 定義方法
rpc GetProductStock(ProductRequest) returns(ProductResponse) {
// http option
option (google.api.http) = {
post: "/v1/prod/prod_id"
body: "*"
};
};
// 定義SayHello方法
rpc SayHello(HelloHTTPRequest) returns (HelloHTTPResponse) {
// http option
option (google.api.http) = {
post: "/example/echo"
body: "*"
};
}
}
生成文件
// pro.pb.go
protoc --go_out=plugins=grpc:./ pro.proto
// pro.pb.gw.go
protoc -I . --grpc-gateway_out ./pb \
--grpc-gateway_opt logtostderr=true \
--grpc-gateway_opt paths=source_relative \
--grpc-gateway_opt generate_unbound_methods=true \
pro.proto
代碼
- grpc 服務器
func main() {
var Address = "127.0.0.1:50052"
listen, err := net.Listen("tcp", Address)
if err != nil {
grpclog.Fatalf("failed to listen: %v", err)
}
// 實例化grpc Server
s := grpc.NewServer()
// 注冊HelloService
pb.RegisterProdServiceServer(s, &service.ProdService{})
grpclog.Println("Listen on " + Address)
s.Serve(listen)
}
- http 服務器
func main() {
// 1. 定義一個context
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
// grpc服務地址
endpoint := "127.0.0.1:50052"
mux := runtime.NewServeMux()
opts := []grpc.DialOption{grpc.WithInsecure()}
// HTTP轉(zhuǎn)grpc
err := pb.RegisterProdServiceHandlerFromEndpoint(ctx, mux, endpoint, opts)
if err != nil {
grpclog.Fatalf("Register handler err:%v\n", err)
}
grpclog.Println("HTTP Listen on 8080")
http.ListenAndServe(":8080", mux)
}
資料
https://github.com/grpc-ecosystem/grpc-gateway
https://www.cnblogs.com/baoshu/p/13510854.html