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

     1  // Copyright (c) HashiCorp, Inc.
     2  // SPDX-License-Identifier: MPL-2.0
     3  
     4  package main
     5  
     6  import (
     7  	"encoding/json"
     8  	"io/ioutil"
     9  
    10  	"github.com/hashicorp/go-plugin"
    11  	"github.com/hashicorp/go-plugin/examples/bidirectional/shared"
    12  )
    13  
    14  // Here is a real implementation of KV that writes to a local file with
    15  // the key name and the contents are the value of the key.
    16  type Counter struct {
    17  }
    18  
    19  type data struct {
    20  	Value int64
    21  }
    22  
    23  func (k *Counter) Put(key string, value int64, a shared.AddHelper) error {
    24  	v, _ := k.Get(key)
    25  
    26  	r, err := a.Sum(v, value)
    27  	if err != nil {
    28  		return err
    29  	}
    30  
    31  	buf, err := json.Marshal(&data{r})
    32  	if err != nil {
    33  		return err
    34  	}
    35  
    36  	return ioutil.WriteFile("kv_"+key, buf, 0644)
    37  }
    38  
    39  func (k *Counter) Get(key string) (int64, error) {
    40  	dataRaw, err := ioutil.ReadFile("kv_" + key)
    41  	if err != nil {
    42  		return 0, err
    43  	}
    44  
    45  	data := &data{}
    46  	err = json.Unmarshal(dataRaw, data)
    47  	if err != nil {
    48  		return 0, err
    49  	}
    50  
    51  	return data.Value, nil
    52  }
    53  
    54  func main() {
    55  	plugin.Serve(&plugin.ServeConfig{
    56  		HandshakeConfig: shared.Handshake,
    57  		Plugins: map[string]plugin.Plugin{
    58  			"counter": &shared.CounterPlugin{Impl: &Counter{}},
    59  		},
    60  
    61  		// A non-nil value here enables gRPC serving for this plugin...
    62  		GRPCServer: plugin.DefaultGRPCServer,
    63  	})
    64  }