github.com/hashicorp/go-plugin@v1.6.0/examples/basic/shared/greeter_interface.go (about)

     1  // Copyright (c) HashiCorp, Inc.
     2  // SPDX-License-Identifier: MPL-2.0
     3  
     4  package shared
     5  
     6  import (
     7  	"net/rpc"
     8  
     9  	"github.com/hashicorp/go-plugin"
    10  )
    11  
    12  // Greeter is the interface that we're exposing as a plugin.
    13  type Greeter interface {
    14  	Greet() string
    15  }
    16  
    17  // Here is an implementation that talks over RPC
    18  type GreeterRPC struct{ client *rpc.Client }
    19  
    20  func (g *GreeterRPC) Greet() string {
    21  	var resp string
    22  	err := g.client.Call("Plugin.Greet", new(interface{}), &resp)
    23  	if err != nil {
    24  		// You usually want your interfaces to return errors. If they don't,
    25  		// there isn't much other choice here.
    26  		panic(err)
    27  	}
    28  
    29  	return resp
    30  }
    31  
    32  // Here is the RPC server that GreeterRPC talks to, conforming to
    33  // the requirements of net/rpc
    34  type GreeterRPCServer struct {
    35  	// This is the real implementation
    36  	Impl Greeter
    37  }
    38  
    39  func (s *GreeterRPCServer) Greet(args interface{}, resp *string) error {
    40  	*resp = s.Impl.Greet()
    41  	return nil
    42  }
    43  
    44  // This is the implementation of plugin.Plugin so we can serve/consume this
    45  //
    46  // This has two methods: Server must return an RPC server for this plugin
    47  // type. We construct a GreeterRPCServer for this.
    48  //
    49  // Client must return an implementation of our interface that communicates
    50  // over an RPC client. We return GreeterRPC for this.
    51  //
    52  // Ignore MuxBroker. That is used to create more multiplexed streams on our
    53  // plugin connection and is a more advanced use case.
    54  type GreeterPlugin struct {
    55  	// Impl Injection
    56  	Impl Greeter
    57  }
    58  
    59  func (p *GreeterPlugin) Server(*plugin.MuxBroker) (interface{}, error) {
    60  	return &GreeterRPCServer{Impl: p.Impl}, nil
    61  }
    62  
    63  func (GreeterPlugin) Client(b *plugin.MuxBroker, c *rpc.Client) (interface{}, error) {
    64  	return &GreeterRPC{client: c}, nil
    65  }