go學習筆記 grpc-gateway和swagger
有關GPRC 的建立 大家 請參考go學習筆記 Windows Go 1.15 以上版本的 GRPC 通訊【自籤CA和雙向認證】,本文同樣會用上文建立的證書。【注意我的環境是win7+go1.15.6】
1:將REST註釋新增到API定義,我們必須安裝grpc-gateway和swagger文件生成器外掛
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 goget -u -v github.com/golang/protobuf/protoc-gen-g
先看看我資料夾的結構吧:
2建立 /api/proto/v1/todo.protor然後生成 ,你可以在這裡獲得proto語言規範:https://developers.google.com/protocol-buffers/docs/proto3,這裡增加了swagger的配置,這個配置的作用是讓swagger把遠端呼叫配置成http,如果沒有這些配置,swagger預設的遠端呼叫就是https的,本文的gRPC-Gateway提供的是http服務,所以要加上這些配置
syntax = "proto3"; package protos;// 1 匯入 gateway 相關的proto 以及 swagger 相關的 proto import "google/api/annotations.proto"; import "protoc-gen-swagger/options/annotations.proto"; // 2 定義 swagger 相關的內容 option (grpc.gateway.protoc_gen_swagger.options.openapiv2_swagger) = { info: { title: "grpc gateway sample"; version: "1.0"; license: { name:"MIT"; }; }; schemes: HTTP; consumes: "application/json"; produces: "application/json"; }; service Greeter { rpc SayHello (HelloRequest) returns (HelloReply) { // 3 標識介面路由 option (google.api.http) = { post: "/hello_world" body: "*" }; } } message HelloRequest { string name = 1; } message HelloReply { string message = 1; }
生成命令如下,
1.如果編譯遇到Interpreting non ascii codepoint 194. 類似錯誤【說白了就是有肉眼看不見的一些東西】,我用的是VSCode,所以安裝外掛vscode-proto3及其依賴的Clang-Format【如果存在報錯clang-format not installed
,需要在系統裡安裝clang-format】安裝後一眼就可以看出來了
2.如果編譯遇到google/api/annotations.proto: File not found.之類問題,需要指定protoc的include 資料夾路徑【我把protoc-3.14.0-win64.zip 解壓到D:\Go,所以我的是D:\Go\include】 ,如果裡面沒有 可以搜尋電腦 , 然後拷貝過去【比如我的是在 D:\GoProject\pkg\mod\cache\download\github.com\grpc-ecosystem\grpc-gateway\@v\v1.16.0\github.com\grpc-ecosystem\[email protected]\third_party\googleapis\google\api 和D:\GoProject\pkg\mod\cache\download\github.com\grpc-ecosystem\grpc-gateway\@v\v1.16.0\github.com\grpc-ecosystem\[email protected]\protoc-gen-swagger\options 這個 路徑太長, 我拷貝到D:\Go\include 】
編譯命令:[google/api/annotations.proto 在D:\Go\include裡面]
//我是在hello 目錄下執行的 protoc -ID:\Go\include -I. --go_out=plugins=grpc:. ./protos/hello.proto protoc -ID:\Go\include -I. --grpc-gateway_out=logtostderr=true:. ./protos/hello.proto protoc -ID:\Go\include -I. --swagger_out=logtostderr=true:. ./protos/hello.proto
3..建立hello/server/services/services.go
package services import ( "context" "fmt" pb "hello/protos" ) type server struct{} func NewServer() *server { return &server{} } func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) { fmt.Println("request: ", in.Name) return &pb.HelloReply{Message: "hello, " + in.Name}, nil }
4.先下載swagger ui的靜態檔案放到 hello\third_party下面。https://github.com/swagger-api/swagger-ui 把這些檔案打包成go檔案。
go get -u github.com/jteeuwen/go-bindata/... //安裝 go-bindata --nocompress -pkg swagger -o gateway/swagger/datafile.go third_party/swagger-ui/...
5.準備閘道器/hello/gateway/gateway.go
package gateway import ( "fmt" "net/http" "path" "strings" assetfs "github.com/elazarl/go-bindata-assetfs" swagger "hello/gateway/swagger" gw "hello/protos" "github.com/grpc-ecosystem/grpc-gateway/runtime" "golang.org/x/net/context" "google.golang.org/grpc" ) /// func HttpRun(gprcPort, httpPort string) error { ctx := context.Background() ctx, cancel := context.WithCancel(ctx) defer cancel() gwmux, err := newGateway(ctx, gprcPort) if err != nil { panic(err) } mux := http.NewServeMux() mux.Handle("/", gwmux) mux.HandleFunc("/swagger/", serveSwaggerFile) serveSwaggerUI(mux) fmt.Println("grpc-gateway listen on localhost" + httpPort) return http.ListenAndServe(httpPort, mux) } func newGateway(ctx context.Context, gprcPort string) (http.Handler, error) { opts := []grpc.DialOption{grpc.WithInsecure()} gwmux := runtime.NewServeMux() if err := gw.RegisterGreeterHandlerFromEndpoint(ctx, gwmux, gprcPort, opts); err != nil { return nil, err } return gwmux, nil } func serveSwaggerFile(w http.ResponseWriter, r *http.Request) { if !strings.HasSuffix(r.URL.Path, "swagger.json") { fmt.Printf("Not Found: %s\r\n", r.URL.Path) http.NotFound(w, r) return } p := strings.TrimPrefix(r.URL.Path, "/swagger/") p = path.Join("../protos", p) fmt.Printf("Serving swagger-file: %s\r\n", p) http.ServeFile(w, r, p) } func serveSwaggerUI(mux *http.ServeMux) { fileServer := http.FileServer(&assetfs.AssetFS{ Asset: swagger.Asset, AssetDir: swagger.AssetDir, Prefix: "third_party/swagger-ui", }) prefix := "/swagger-ui/" mux.Handle(prefix, http.StripPrefix(prefix, fileServer)) }
6.準備f服務 /hello/server/main.go
package main import ( "fmt" pb "hello/protos" "hello/server/services" "log" "net" "hello/gateway" "google.golang.org/grpc" ) func main() { grpcPort := ":9090" httpPort := ":8080" lis, err := net.Listen("tcp", grpcPort) if err != nil { log.Fatalf("failed to listen: %v", err) } go gateway.HttpRun(grpcPort, httpPort) s := grpc.NewServer() pb.RegisterGreeterServer(s, services.NewServer()) fmt.Println("rpc services started, listen on localhost" + grpcPort) s.Serve(lis) }
執行結果如下:
D:\GoProject\src\hello>cd server D:\GoProject\src\hello\server>go run main.go rpc services started, listen on localhost:9090 grpc-gateway listen on localhost:8080
訪問http://localhost:8080/swagger/hello.swagger.json正常
7.建立客戶端的main.go【分為 gprc 和http 部分】hello/client/main.go
package main import ( "context" "encoding/json" "fmt" pb "hello/protos" sv "hello/server/services" "io/ioutil" "net/http" "strings" "google.golang.org/grpc" ) func main() { req := pb.HelloRequest{Name: "gavin"} // GRPC conn, err := grpc.Dial("localhost:9090", grpc.WithInsecure()) if err != nil { fmt.Println(err) return } defer conn.Close() c := sv.NewServer() r, err := c.SayHello(context.Background(), &req) if err != nil { fmt.Println(err) } // 列印返回值 fmt.Println(r) fmt.Println("http Start......................") //http requestByte, _ := json.Marshal(req) request, _ := http.NewRequest("POST", "http://localhost:8080/hello_world", strings.NewReader(string(requestByte))) request.Header.Set("Content-Type", "application/json") response, _ := http.DefaultClient.Do(request) bodyBytes, err := ioutil.ReadAll(response.Body) defer response.Body.Close() fmt.Println(string(bodyBytes)) }
執行效果:
D:\GoProject\src\hello>cd client D:\GoProject\src\hello\client>go run main.go request: gavin message:"hello, gavin" http Start...................... {"message":"hello, gavin"}
原始碼下載https://download.csdn.net/download/dz45693/13995056
參考:
https://www.cnblogs.com/catcher1994/archive/2004/01/13/11869532.html