Skip to content

Commit

Permalink
fix: move client logic to a function that always return (#262)
Browse files Browse the repository at this point in the history
This commit fixes a bug in the `main()` that runs `defer client.Kill()` but use `os.Exit()` to finish the program; defer is just executed when a function returns. Because of that, the plugin was never closed.

To fix it, I moved the client logic to a separate function that always returns and let the `os.Exit()` for the `main()`. It will guarantee that we will always call the `defer client.Kill()`.
  • Loading branch information
willyrgf authored Oct 25, 2023
1 parent c69982f commit 017b758
Showing 1 changed file with 18 additions and 13 deletions.
31 changes: 18 additions & 13 deletions examples/grpc/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,7 @@ import (
"github.com/hashicorp/go-plugin/examples/grpc/shared"
)

func main() {
// We don't want to see the plugin logs.
log.SetOutput(ioutil.Discard)

func run() error {
// We're a host. Start by launching the plugin process.
client := plugin.NewClient(&plugin.ClientConfig{
HandshakeConfig: shared.Handshake,
Expand All @@ -31,15 +28,13 @@ func main() {
// Connect via RPC
rpcClient, err := client.Client()
if err != nil {
fmt.Println("Error:", err.Error())
os.Exit(1)
return err
}

// Request the plugin
raw, err := rpcClient.Dispense("kv_grpc")
if err != nil {
fmt.Println("Error:", err.Error())
os.Exit(1)
return err
}

// We should have a KV store now! This feels like a normal interface
Expand All @@ -50,22 +45,32 @@ func main() {
case "get":
result, err := kv.Get(os.Args[1])
if err != nil {
fmt.Println("Error:", err.Error())
os.Exit(1)
return err
}

fmt.Println(string(result))

case "put":
err := kv.Put(os.Args[1], []byte(os.Args[2]))
if err != nil {
fmt.Println("Error:", err.Error())
os.Exit(1)
return err
}

default:
fmt.Printf("Please only use 'get' or 'put', given: %q", os.Args[0])
return fmt.Errorf("Please only use 'get' or 'put', given: %q", os.Args[0])
}

return nil
}

func main() {
// We don't want to see the plugin logs.
log.SetOutput(ioutil.Discard)

if err := run(); err != nil {
fmt.Printf("error: %+v\n", err)
os.Exit(1)
}

os.Exit(0)
}

0 comments on commit 017b758

Please sign in to comment.