github.com/ladydascalie/elvish@v0.0.0-20170703214355-2964dd3ece7f/daemon/api/client.go (about) 1 package api 2 3 import ( 4 "errors" 5 "net/rpc" 6 "sync" 7 ) 8 9 var ErrDaemonOffline = errors.New("daemon offline") 10 11 type Client struct { 12 sockPath string 13 rpcClient *rpc.Client 14 waits sync.WaitGroup 15 } 16 17 func NewClient(sockPath string) *Client { 18 return &Client{sockPath, nil, sync.WaitGroup{}} 19 } 20 21 func (c *Client) SockPath() string { 22 return c.sockPath 23 } 24 25 func (c *Client) Waits() *sync.WaitGroup { 26 return &c.waits 27 } 28 29 func (c *Client) CallDaemon(f string, req, res interface{}) error { 30 err := c.connect() 31 if err != nil { 32 return err 33 } 34 err = c.rpcClient.Call(ServiceName+"."+f, req, res) 35 if err == rpc.ErrShutdown { 36 // Clear rpcClient so as to reconnect next time 37 c.rpcClient = nil 38 } 39 return err 40 } 41 42 func (c *Client) Close() error { 43 c.waits.Wait() 44 return c.rpcClient.Close() 45 } 46 47 func (c *Client) connect() error { 48 rpcClient, err := rpc.Dial("unix", c.sockPath) 49 if err != nil { 50 return err 51 } 52 c.rpcClient = rpcClient 53 return nil 54 }