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

     1  package rpc
     2  
     3  import (
     4  	"encoding/gob"
     5  	"errors"
     6  	"fmt"
     7  	"net/rpc"
     8  	"sync"
     9  
    10  	"github.com/hashicorp/otto/app"
    11  )
    12  
    13  // nextId is the next ID to use for names registered.
    14  var nextId uint32 = 0
    15  var nextLock sync.Mutex
    16  
    17  func init() {
    18  	// We need this to avoid gob errors in logs when responding to UI
    19  	// calls (which are a no-op response).
    20  	gob.Register(new(struct{}))
    21  }
    22  
    23  // Register registers an Otto thing with the RPC server and returns
    24  // the name it is registered under.
    25  func Register(server *rpc.Server, thing interface{}) (name string, err error) {
    26  	nextLock.Lock()
    27  	defer nextLock.Unlock()
    28  
    29  	switch t := thing.(type) {
    30  	case app.App:
    31  		name = fmt.Sprintf("Otto%d", nextId)
    32  		err = server.RegisterName(name, &AppServer{App: t})
    33  	default:
    34  		return "", errors.New("Unknown type to register for RPC server.")
    35  	}
    36  
    37  	nextId += 1
    38  	return
    39  }