srpc/client.go

51 lines
946 B
Go

package srpc
import (
"bytes"
"errors"
"io"
"net"
)
type Client struct {
ed IEncoderDecoder
conn IRPCConn
}
func (client *Client) Call(funcName string, args ...interface{}) (ret []byte, err error) {
defer client.conn.Close()
var b bytes.Buffer
enc := client.ed.NewEncoder(&b)
for _, a := range args {
enc.Encode(a)
}
payload := b.Bytes()
req := RPCRequest{funcName, payload}
if err = client.conn.SendRequest(&req); err != nil {
return nil, err
}
var response *RPCResponse
if response, err = client.conn.ReceiveResponse(); err != nil {
return nil, err
}
if response.Status != RPCOK {
err = errors.New("srpc - Response contained error: '" + response.Error + "'")
}
return response.Payload, err
}
func (client *Client) NewDecoder(r io.Reader) IDecoder {
return client.ed.NewDecoder(r)
}
func NewClient(conn net.Conn) *Client {
return &Client{NewEncoderDecoder(), NewTCPConn(conn, NewEncoderDecoder())}
}