proto工具插件集
此开源图书由ithaiq原创,创作不易转载请注明出处
grpc提供http接口调用(go get github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway)
package main
import (
"context"
"flag"
"net/http"
"github.com/golang/glog"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"google.golang.org/grpc"
gw "github.com/yourorg/yourrepo/proto/gen/go/your/service/v1/your_service" // Update
)
var (
// command-line options:
// gRPC server endpoint
grpcServerEndpoint = flag.String("grpc-server-endpoint", "localhost:9090", "gRPC server endpoint")
)
func run() error {
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
// Register gRPC server endpoint
// Note: Make sure the gRPC server is running properly and accessible
mux := runtime.NewServeMux()
opts := []grpc.DialOption{grpc.WithInsecure()}
err := gw.RegisterYourServiceHandlerFromEndpoint(ctx, mux, *grpcServerEndpoint, opts)
if err != nil {
return err
}
// Start HTTP server (and proxy calls to gRPC server endpoint)
return http.ListenAndServe(":8081", mux)
}
func main() {
flag.Parse()
defer glog.Flush()
if err := run(); err != nil {
glog.Fatal(err)
}
}
swagger接口文档(go get github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger)
import "google/api/annotations.proto";
import "protoc-gen-swagger/options/annotations.proto";
option (grpc.gateway.protoc_gen_swagger.options.openapiv2_swagger) = {
info: {
title: "商品服务接口文档";
version: "1.0";
license: {
name: "MIT";
};
};
schemes: HTTP;
};
service GoodsService {
rpc GetGoodsList(GoodsListRequest) returns (GoodsListResponse){
option (google.api.http) = {
post: "/zt_goods/goodsService/getGoodsList"
body: "*"
};
}
}
参数校验(go get github.com/envoyproxy/protoc-gen-validate)
import "validate.proto";
message UserRequest {
//id必须大于1
int32 id=1[(validate.rules).int32.gt = 1];
}
字段tag修改&引入时间类型(go get github.com/favadi/protoc-go-inject-tag)
import "google/protobuf/timestamp.proto";
message UserRequest {
//时间
// @inject_tag: json:"xxx"
google.protobuf.Timestamp time = 2;
}
pb命令
OUTPUT=/tmp/go
TARGET=$OUTPUT/microservices/common/protos
SWAGGER_PATH=$(go list -f '{{.Dir}}' -m github.com/grpc-ecosystem/grpc-gateway)
GOOGLE_API_PATH=$SWAGGER_PATH/third_party/googleapis
VALIDATE_PATH=$(go list -f '{{.Dir}}' -m github.com/envoyproxy/protoc-gen-validate)
for f in `find ./ -name "$1.proto"`;do
file_name=$(basename $f .proto)
echo $file_name
protoc -I. $f -I$VALIDATE_PATH -I$SWAGGER_PATH -I$GOOGLE_API_PATH \
--micro_out=$OUTPUT --go_out=plugins=grpc:$OUTPUT --validate_out=lang=go:$OUTPUT
protoc -I. $f -I$VALIDATE_PATH -I$SWAGGER_PATH -I$GOOGLE_API_PATH --grpc-gateway_out=logtostderr=true,register_func_suffix=Gw:$OUTPUT
protoc -I. $f -I$VALIDATE_PATH -I$SWAGGER_PATH -I$GOOGLE_API_PATH --swagger_out=logtostderr=true:$TARGET/$file_name/
generateSwagger $TARGET/$file_name $file_name
done
protoc-go-inject-tag -input=xxx.pb.go
最后更新于
这有帮助吗?