0

是否可以在同一云运行服务器上同时运行 grpc 和 rest API?我发现了一些博客并尝试在我的本地系统上编写和运行它,但它给出了错误代码 14。

func main() {
    ctx := context.Background()

    grpcServer := grpc.NewServer()
    admin.RegisterMessageServiceServer(grpcServer, &server.AdminService{})

    conn, err := grpc.DialContext(ctx, "localhost:8080", grpc.WithInsecure())
    if err != nil {
        log.Fatalln("failed to dial server:", err)
    }

    router := runtime.NewServeMux()
    if err = admin.RegisterMessageServiceHandler(ctx, router, conn); err != nil {
        log.Fatalln("failed to register gateway", err)
    }

    log.Println("starting server on :8080")
    if err := http.ListenAndServe(":8080", httpGrpcRouter(grpcServer, router)); err != nil {
        log.Fatalln("failed to start the server: ", err)
    }
}

// handler both api & grpc request same time on same port using this router
func httpGrpcRouter(grpcServer *grpc.Server, httpHandler http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        if r.ProtoMajor == 2 && strings.Contains(r.Header.Get("Content-Type"), "application/grpc") {
            log.Println("GRPC request")
            grpcServer.ServeHTTP(w, r)
        } else {
            log.Println("HTTP request")
            httpHandler.ServeHTTP(w, r)
        }
    })
}

我的原型文件包含这样的服务:

service MessageService {
  rpc Create(CreateRequest) returns (CreateResponse) {
    option (google.api.http) = {
      post: "/v1/admin/{site}/message"
      body: "*"
    };
  };
  rpc Get(GetRequest) returns(GetResponse){
    option (google.api.http) = {
      get: "/v1/admin/{site}/message/{messageId}"
    };
  };
  rpc List(ListRequest) returns(ListResponse){
    option (google.api.http) = {
      get: "/v1/admin/{site}/message"
    };
  };
}

现在,如果我从 BloomRPC 客户端运行它,则会收到以下错误:

{
  "error": "14 UNAVAILABLE: Trying to connect an http1.x server"
}

如果尝试从邮递员那里访问其余 API ( http://127.0.0.1:8080/v1/admin/test/message ),则会出现以下错误:

{
    "error": "connection closed",
    "code": 14,
    "message": "connection closed"
}

如果我只运行 GRPC 服务并从 BloomRPC 客户端检查它,那么它工作正常。这是工作 GRPC 主要功能:

func main() {
    grpcServer := grpc.NewServer()
    admin.RegisterMessageServiceServer(grpcServer, &server.AdminService{})

    listen, err := net.Listen("tcp", ":8080")
    if err != nil {
        log.Fatal(err)
    }
    log.Printf("Starting: gRPC Listener [%s]\n", ":8080")
    log.Fatal(grpcServer.Serve(listen))
}

尝试同时运行 GRPC 和 rest api(在同一端口上)时,我做错了什么。

谢谢

4

0 回答 0