Skip to content

Commit 017b758

Browse files
authored
fix: move client logic to a function that always return (#262)
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()`.
1 parent c69982f commit 017b758

File tree

1 file changed

+18
-13
lines changed

1 file changed

+18
-13
lines changed

examples/grpc/main.go

+18-13
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,7 @@ import (
1414
"github.com/hashicorp/go-plugin/examples/grpc/shared"
1515
)
1616

17-
func main() {
18-
// We don't want to see the plugin logs.
19-
log.SetOutput(ioutil.Discard)
20-
17+
func run() error {
2118
// We're a host. Start by launching the plugin process.
2219
client := plugin.NewClient(&plugin.ClientConfig{
2320
HandshakeConfig: shared.Handshake,
@@ -31,15 +28,13 @@ func main() {
3128
// Connect via RPC
3229
rpcClient, err := client.Client()
3330
if err != nil {
34-
fmt.Println("Error:", err.Error())
35-
os.Exit(1)
31+
return err
3632
}
3733

3834
// Request the plugin
3935
raw, err := rpcClient.Dispense("kv_grpc")
4036
if err != nil {
41-
fmt.Println("Error:", err.Error())
42-
os.Exit(1)
37+
return err
4338
}
4439

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

5751
fmt.Println(string(result))
5852

5953
case "put":
6054
err := kv.Put(os.Args[1], []byte(os.Args[2]))
6155
if err != nil {
62-
fmt.Println("Error:", err.Error())
63-
os.Exit(1)
56+
return err
6457
}
6558

6659
default:
67-
fmt.Printf("Please only use 'get' or 'put', given: %q", os.Args[0])
60+
return fmt.Errorf("Please only use 'get' or 'put', given: %q", os.Args[0])
61+
}
62+
63+
return nil
64+
}
65+
66+
func main() {
67+
// We don't want to see the plugin logs.
68+
log.SetOutput(ioutil.Discard)
69+
70+
if err := run(); err != nil {
71+
fmt.Printf("error: %+v\n", err)
6872
os.Exit(1)
6973
}
74+
7075
os.Exit(0)
7176
}

0 commit comments

Comments
 (0)