github.com/hashicorp/go-plugin@v1.6.0/examples/basic/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  	"log"
     9  	"os"
    10  	"os/exec"
    11  
    12  	hclog "github.com/hashicorp/go-hclog"
    13  	"github.com/hashicorp/go-plugin"
    14  	"github.com/hashicorp/go-plugin/examples/basic/shared"
    15  )
    16  
    17  func main() {
    18  	// Create an hclog.Logger
    19  	logger := hclog.New(&hclog.LoggerOptions{
    20  		Name:   "plugin",
    21  		Output: os.Stdout,
    22  		Level:  hclog.Debug,
    23  	})
    24  
    25  	// We're a host! Start by launching the plugin process.
    26  	client := plugin.NewClient(&plugin.ClientConfig{
    27  		HandshakeConfig: handshakeConfig,
    28  		Plugins:         pluginMap,
    29  		Cmd:             exec.Command("./plugin/greeter"),
    30  		Logger:          logger,
    31  	})
    32  	defer client.Kill()
    33  
    34  	// Connect via RPC
    35  	rpcClient, err := client.Client()
    36  	if err != nil {
    37  		log.Fatal(err)
    38  	}
    39  
    40  	// Request the plugin
    41  	raw, err := rpcClient.Dispense("greeter")
    42  	if err != nil {
    43  		log.Fatal(err)
    44  	}
    45  
    46  	// We should have a Greeter now! This feels like a normal interface
    47  	// implementation but is in fact over an RPC connection.
    48  	greeter := raw.(shared.Greeter)
    49  	fmt.Println(greeter.Greet())
    50  }
    51  
    52  // handshakeConfigs are used to just do a basic handshake between
    53  // a plugin and host. If the handshake fails, a user friendly error is shown.
    54  // This prevents users from executing bad plugins or executing a plugin
    55  // directory. It is a UX feature, not a security feature.
    56  var handshakeConfig = plugin.HandshakeConfig{
    57  	ProtocolVersion:  1,
    58  	MagicCookieKey:   "BASIC_PLUGIN",
    59  	MagicCookieValue: "hello",
    60  }
    61  
    62  // pluginMap is the map of plugins we can dispense.
    63  var pluginMap = map[string]plugin.Plugin{
    64  	"greeter": &shared.GreeterPlugin{},
    65  }