forked from porthos-rpc/porthos-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
103 lines (82 loc) · 1.97 KB
/
client.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package porthos
import (
"time"
"github.com/porthos-rpc/porthos-go/log"
"github.com/streadway/amqp"
)
// Client is an entry point for making remote calls.
type Client struct {
serviceName string
defaultTTL time.Duration
channel *amqp.Channel
deliveryChannel <-chan amqp.Delivery
responseQueue *amqp.Queue
broker *Broker
}
// NewClient creates a new instance of Client, responsible for making remote calls.
func NewClient(b *Broker, serviceName string, defaultTTL time.Duration) (*Client, error) {
ch, err := b.openChannel()
if err != nil {
return nil, err
}
// create the response queue (let the amqp server to pick a name for us)
q, err := ch.QueueDeclare("", false, false, true, false, nil)
if err != nil {
ch.Close()
return nil, err
}
dc, err := ch.Consume(
q.Name, // queue
"", // consumer
false, // auto-ack
false, // exclusive
false, // no-local
false, // no-wait
nil, // args
)
if err != nil {
ch.Close()
return nil, err
}
c := &Client{
serviceName,
defaultTTL,
ch,
dc,
&q,
b,
}
c.start()
return c, nil
}
func (c *Client) start() {
go func() {
for d := range c.deliveryChannel {
c.processResponse(d)
}
}()
}
func (c *Client) processResponse(d amqp.Delivery) {
d.Ack(false)
log.Debug("Ack. Received response in '%s' for slot: '%d'", d.RoutingKey, []byte(d.CorrelationId))
address := c.unmarshallCorrelationID(d.CorrelationId)
statusCode := d.Headers["statusCode"].(int32)
res := getSlot(address)
res.sendResponse(ClientResponse{
Content: d.Body,
ContentType: d.ContentType,
StatusCode: statusCode,
Headers: *NewHeadersFromMap(d.Headers),
})
}
// Call prepares a remote call.
func (c *Client) Call(method string) *call {
return newCall(c, method)
}
// Close the client and AMQP chanel.
func (c *Client) Close() {
c.channel.Close()
}
func (c *Client) unmarshallCorrelationID(correlationID string) uintptr {
return BytesToUintptr([]byte(correlationID))
}