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

     1  // Copyright (c) HashiCorp, Inc.
     2  // SPDX-License-Identifier: MPL-2.0
     3  
     4  package shared
     5  
     6  import (
     7  	"context"
     8  
     9  	"github.com/hashicorp/go-plugin/examples/grpc/proto"
    10  )
    11  
    12  // GRPCClient is an implementation of KV that talks over RPC.
    13  type GRPCClient struct{ client proto.KVClient }
    14  
    15  func (m *GRPCClient) Put(key string, value []byte) error {
    16  	_, err := m.client.Put(context.Background(), &proto.PutRequest{
    17  		Key:   key,
    18  		Value: value,
    19  	})
    20  	return err
    21  }
    22  
    23  func (m *GRPCClient) Get(key string) ([]byte, error) {
    24  	resp, err := m.client.Get(context.Background(), &proto.GetRequest{
    25  		Key: key,
    26  	})
    27  	if err != nil {
    28  		return nil, err
    29  	}
    30  
    31  	return resp.Value, nil
    32  }
    33  
    34  // Here is the gRPC server that GRPCClient talks to.
    35  type GRPCServer struct {
    36  	// This is the real implementation
    37  	Impl KV
    38  }
    39  
    40  func (m *GRPCServer) Put(
    41  	ctx context.Context,
    42  	req *proto.PutRequest) (*proto.Empty, error) {
    43  	return &proto.Empty{}, m.Impl.Put(req.Key, req.Value)
    44  }
    45  
    46  func (m *GRPCServer) Get(
    47  	ctx context.Context,
    48  	req *proto.GetRequest) (*proto.GetResponse, error) {
    49  	v, err := m.Impl.Get(req.Key)
    50  	return &proto.GetResponse{Value: v}, err
    51  }