srpc/client.go

51 lines
946 B
Go
Raw Normal View History

2019-10-22 01:32:56 +02:00
package srpc
2020-02-10 02:53:05 +01:00
import (
"bytes"
"errors"
2020-02-10 02:53:05 +01:00
"io"
"net"
)
type Client struct {
ed IEncoderDecoder
conn IRPCConn
2020-02-10 02:53:05 +01:00
}
func (client *Client) Call(funcName string, args ...interface{}) (ret []byte, err error) {
defer client.conn.Close()
2020-02-10 02:53:05 +01:00
var b bytes.Buffer
enc := client.ed.NewEncoder(&b)
for _, a := range args {
enc.Encode(a)
}
payload := b.Bytes()
req := RPCRequest{funcName, payload}
2020-02-10 02:53:05 +01:00
if err = client.conn.SendRequest(&req); err != nil {
return nil, err
}
2020-02-10 02:53:05 +01:00
var response *RPCResponse
if response, err = client.conn.ReceiveResponse(); err != nil {
return nil, err
}
2020-02-10 02:53:05 +01:00
if response.Status != RPCOK {
err = errors.New("srpc - Response contained error: '" + response.Error + "'")
2020-02-14 01:51:30 +01:00
}
return response.Payload, err
2020-02-10 02:53:05 +01:00
}
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())}
2019-10-22 01:32:56 +02:00
}