企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
## 下载依赖库 ``` 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 ``` `最重要的一步`: 这里把编译生成的protoc-gen-go protoc-gen-grpc-gateway二进制文件的目录放gopath/bin中,把$GOPATH/bin放入$PATH中。 ``` https://www.golangtc.com/download/package 安装需要翻墙的包 ``` ``` https://github.com/googleapis/googleapis/tree/master/google protobuf依赖 ``` ## protobuf 文件修改 和之前的proto文件比较,新的文件增了 ``` import "google/api/annotations.proto"; ``` 和 ``` option (google.api.http) = { post: "/v1/example/echo" body: "*" }; ``` ## 生成gw文件 ``` python -m grpc_tools.protoc -I. -I/Users/congzaifeng/go/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis --go_out=. --grpc-gateway_out=logtostderr=true:. helloworld.proto -I/Users/congzaifeng/go/src/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway ``` ## 编写gateway文件 ``` package main import ( "flag" "net/http" "github.com/golang/glog" "github.com/grpc-ecosystem/grpc-gateway/runtime" "golang.org/x/net/context" "google.golang.org/grpc" gw "grpc-helloworld-gateway/helloworld" ) var ( echoEndpoint = flag.String("echo_endpoint", "localhost:50051", "endpoint of YourService") ) func run() error { ctx := context.Background() ctx, cancel := context.WithCancel(ctx) defer cancel() mux := runtime.NewServeMux() opts := []grpc.DialOption{grpc.WithInsecure()} err := gw.RegisterGreeterHandlerFromEndpoint(ctx, mux, *echoEndpoint, opts) if err != nil { return err } return http.ListenAndServe(":8080", mux) } func main() { flag.Parse() defer glog.Flush() if err := run(); err != nil { glog.Fatal(err) } } ```