github.com/hashicorp/go-plugin@v1.6.0/examples/grpc/main.go (about) 1 // Copyright (c) HashiCorp, Inc. 2 // SPDX-License-Identifier: MPL-2.0 3 4 package main 5 6 import ( 7 "fmt" 8 "io/ioutil" 9 "log" 10 "os" 11 "os/exec" 12 13 "github.com/hashicorp/go-plugin" 14 "github.com/hashicorp/go-plugin/examples/grpc/shared" 15 ) 16 17 func run() error { 18 // We're a host. Start by launching the plugin process. 19 client := plugin.NewClient(&plugin.ClientConfig{ 20 HandshakeConfig: shared.Handshake, 21 Plugins: shared.PluginMap, 22 Cmd: exec.Command("sh", "-c", os.Getenv("KV_PLUGIN")), 23 AllowedProtocols: []plugin.Protocol{ 24 plugin.ProtocolNetRPC, plugin.ProtocolGRPC}, 25 }) 26 defer client.Kill() 27 28 // Connect via RPC 29 rpcClient, err := client.Client() 30 if err != nil { 31 return err 32 } 33 34 // Request the plugin 35 raw, err := rpcClient.Dispense("kv_grpc") 36 if err != nil { 37 return err 38 } 39 40 // We should have a KV store now! This feels like a normal interface 41 // implementation but is in fact over an RPC connection. 42 kv := raw.(shared.KV) 43 os.Args = os.Args[1:] 44 switch os.Args[0] { 45 case "get": 46 result, err := kv.Get(os.Args[1]) 47 if err != nil { 48 return err 49 } 50 51 fmt.Println(string(result)) 52 53 case "put": 54 err := kv.Put(os.Args[1], []byte(os.Args[2])) 55 if err != nil { 56 return err 57 } 58 59 default: 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) 72 os.Exit(1) 73 } 74 75 os.Exit(0) 76 }