OSDN Git Service

add package
[bytom/vapor.git] / vendor / github.com / hashicorp / go-plugin / examples / bidirectional / main.go
1 package main
2
3 import (
4         "fmt"
5         "io/ioutil"
6         "log"
7         "os"
8         "os/exec"
9         "strconv"
10
11         "github.com/hashicorp/go-plugin"
12         "github.com/hashicorp/go-plugin/examples/bidirectional/shared"
13 )
14
15 type addHelper struct{}
16
17 func (*addHelper) Sum(a, b int64) (int64, error) {
18         return a + b, nil
19 }
20
21 func main() {
22         // We don't want to see the plugin logs.
23         log.SetOutput(ioutil.Discard)
24
25         // We're a host. Start by launching the plugin process.
26         client := plugin.NewClient(&plugin.ClientConfig{
27                 HandshakeConfig: shared.Handshake,
28                 Plugins:         shared.PluginMap,
29                 Cmd:             exec.Command("sh", "-c", os.Getenv("COUNTER_PLUGIN")),
30                 AllowedProtocols: []plugin.Protocol{
31                         plugin.ProtocolNetRPC, plugin.ProtocolGRPC},
32         })
33         defer client.Kill()
34
35         // Connect via RPC
36         rpcClient, err := client.Client()
37         if err != nil {
38                 fmt.Println("Error:", err.Error())
39                 os.Exit(1)
40         }
41
42         // Request the plugin
43         raw, err := rpcClient.Dispense("counter")
44         if err != nil {
45                 fmt.Println("Error:", err.Error())
46                 os.Exit(1)
47         }
48
49         // We should have a Counter store now! This feels like a normal interface
50         // implementation but is in fact over an RPC connection.
51         counter := raw.(shared.Counter)
52
53         os.Args = os.Args[1:]
54         switch os.Args[0] {
55         case "get":
56                 result, err := counter.Get(os.Args[1])
57                 if err != nil {
58                         fmt.Println("Error:", err.Error())
59                         os.Exit(1)
60                 }
61
62                 fmt.Println(result)
63
64         case "put":
65                 i, err := strconv.Atoi(os.Args[2])
66                 if err != nil {
67                         fmt.Println("Error:", err.Error())
68                         os.Exit(1)
69                 }
70
71                 err = counter.Put(os.Args[1], int64(i), &addHelper{})
72                 if err != nil {
73                         fmt.Println("Error:", err.Error())
74                         os.Exit(1)
75                 }
76
77         default:
78                 fmt.Println("Please only use 'get' or 'put'")
79                 os.Exit(1)
80         }
81 }