github.com/bhameyie/otto@v0.2.1-0.20160406174117-16052efa52ec/rpc/ui.go (about)

     1  package rpc
     2  
     3  import (
     4  	"log"
     5  	"net/rpc"
     6  
     7  	"github.com/hashicorp/otto/ui"
     8  )
     9  
    10  // Ui is an implementatin of ui.Ui that communicates over RPC.
    11  type Ui struct {
    12  	Client *rpc.Client
    13  	Name   string
    14  }
    15  
    16  func (i *Ui) Header(msg string)  { i.basicCall("Header", msg) }
    17  func (i *Ui) Message(msg string) { i.basicCall("Message", msg) }
    18  func (i *Ui) Raw(msg string)     { i.basicCall("Raw", msg) }
    19  
    20  func (i *Ui) Input(opts *ui.InputOpts) (string, error) {
    21  	var resp UiInputResponse
    22  	err := i.Client.Call(i.Name+".Input", opts, &resp)
    23  	if err != nil {
    24  		return "", err
    25  	}
    26  	if resp.Error != nil {
    27  		err = resp.Error
    28  		return "", err
    29  	}
    30  
    31  	return resp.Value, nil
    32  }
    33  
    34  func (i *Ui) basicCall(kind, msg string) {
    35  	err := i.Client.Call(i.Name+"."+kind, msg, nil)
    36  	if err != nil {
    37  		log.Printf("[ERR] rpc/ui: %s", err)
    38  	}
    39  }
    40  
    41  type UiInputResponse struct {
    42  	Value string
    43  	Error *BasicError
    44  }
    45  
    46  // UiServer is a net/rpc compatible structure for serving
    47  // a Ui. This should not be used directly.
    48  type UiServer struct {
    49  	Ui ui.Ui
    50  }
    51  
    52  func (s *UiServer) Header(msg string, reply *interface{}) error {
    53  	s.Ui.Header(msg)
    54  	*reply = new(struct{})
    55  	return nil
    56  }
    57  
    58  func (s *UiServer) Message(msg string, reply *interface{}) error {
    59  	s.Ui.Message(msg)
    60  	*reply = new(struct{})
    61  	return nil
    62  }
    63  
    64  func (s *UiServer) Raw(msg string, reply *interface{}) error {
    65  	s.Ui.Raw(msg)
    66  	*reply = new(struct{})
    67  	return nil
    68  }
    69  
    70  func (s *UiServer) Input(
    71  	opts *ui.InputOpts,
    72  	reply *UiInputResponse) error {
    73  	value, err := s.Ui.Input(opts)
    74  	*reply = UiInputResponse{
    75  		Value: value,
    76  		Error: NewBasicError(err),
    77  	}
    78  
    79  	return nil
    80  }