3
votes

Hi I'm trying to connect a gRPC client to the server but even though the connection is succesful I get the following error when querying it from the graphql resolvers. However if I dial directly from the resolver everything works so it has to do with the client not leaving the connection open.

rpc error: code = Canceled desc = grpc: the client connection is closing

client.go

var kacp = keepalive.ClientParameters{
    Time:                10 * time.Second, // send pings every 10 seconds if there is no activity
    Timeout:             time.Second,      // wait 1 second for ping back
    PermitWithoutStream: true,             // send pings even without active streams
}

func gqlHandler() http.HandlerFunc {

    conn, err := grpc.Dial("127.0.0.1:50051", grpc.WithInsecure(), 
    grpc.WithKeepaliveParams(kacp),
    grpc.WithBlock())

    if err != nil {
        panic(err)
    }
    defer conn.Close()

    db := proto.NewPlatformDBClient(conn)

    gh := handler.GraphQL(platform.NewExecutableSchema(platform.Config{Resolvers: &platform.Resolver{
        DB: db,
    }}))

    gh = cors.Disable(gh)

    return gh
}
1
I have a similar question but with a Kotlin for Android client. Could you find any solution to keeping the connection open?Daniel

1 Answers

7
votes

Its because the defer conn.Close() command will be executed before the connection is even used.

From the go blog

A defer statement pushes a function call onto a list. The list of saved calls is executed after the surrounding function returns.

So you would remove the line defer conn.Close() and close the connection after it is not used anymore.