blob: 28791ccd0c0cd6171e8183c140bb152ea123464c [file] [log] [blame]
D. Can Celasun4f77ab82017-09-21 15:21:00 +02001package thrift
2
John Boiles57852792018-01-05 14:37:05 -08003import (
4 "context"
5 "fmt"
6)
7
8type TClient interface {
9 Call(ctx context.Context, method string, args, result TStruct) error
10}
D. Can Celasun4f77ab82017-09-21 15:21:00 +020011
12type TStandardClient struct {
13 seqId int32
14 iprot, oprot TProtocol
15}
16
17// TStandardClient implements TClient, and uses the standard message format for Thrift.
18// It is not safe for concurrent use.
19func NewTStandardClient(inputProtocol, outputProtocol TProtocol) *TStandardClient {
20 return &TStandardClient{
21 iprot: inputProtocol,
22 oprot: outputProtocol,
23 }
24}
25
John Boiles57852792018-01-05 14:37:05 -080026func (p *TStandardClient) Send(ctx context.Context, oprot TProtocol, seqId int32, method string, args TStruct) error {
D. Can Celasun4f77ab82017-09-21 15:21:00 +020027 if err := oprot.WriteMessageBegin(method, CALL, seqId); err != nil {
28 return err
29 }
30 if err := args.Write(oprot); err != nil {
31 return err
32 }
33 if err := oprot.WriteMessageEnd(); err != nil {
34 return err
35 }
John Boiles57852792018-01-05 14:37:05 -080036 return oprot.Flush(ctx)
D. Can Celasun4f77ab82017-09-21 15:21:00 +020037}
38
39func (p *TStandardClient) Recv(iprot TProtocol, seqId int32, method string, result TStruct) error {
40 rMethod, rTypeId, rSeqId, err := iprot.ReadMessageBegin()
41 if err != nil {
42 return err
43 }
44
45 if method != rMethod {
46 return NewTApplicationException(WRONG_METHOD_NAME, fmt.Sprintf("%s: wrong method name", method))
47 } else if seqId != rSeqId {
48 return NewTApplicationException(BAD_SEQUENCE_ID, fmt.Sprintf("%s: out of order sequence response", method))
49 } else if rTypeId == EXCEPTION {
50 var exception tApplicationException
51 if err := exception.Read(iprot); err != nil {
52 return err
53 }
54
55 if err := iprot.ReadMessageEnd(); err != nil {
56 return err
57 }
58
59 return &exception
60 } else if rTypeId != REPLY {
61 return NewTApplicationException(INVALID_MESSAGE_TYPE_EXCEPTION, fmt.Sprintf("%s: invalid message type", method))
62 }
63
64 if err := result.Read(iprot); err != nil {
65 return err
66 }
67
68 return iprot.ReadMessageEnd()
69}
70
John Boiles57852792018-01-05 14:37:05 -080071func (p *TStandardClient) Call(ctx context.Context, method string, args, result TStruct) error {
D. Can Celasun4f77ab82017-09-21 15:21:00 +020072 p.seqId++
73 seqId := p.seqId
74
John Boiles57852792018-01-05 14:37:05 -080075 if err := p.Send(ctx, p.oprot, seqId, method, args); err != nil {
D. Can Celasun4f77ab82017-09-21 15:21:00 +020076 return err
77 }
78
79 // method is oneway
80 if result == nil {
81 return nil
82 }
83
84 return p.Recv(p.iprot, seqId, method, result)
85}