Request / Reply
Beyond just sending messages, Grav can be used to make requests and get replies. This can be useful for service-to-service communication, RPC-style message, and more.
1
package main
2
3
import (
4
"fmt"
5
6
"github.com/suborbital/grav/grav"
7
)
8
9
func requestReply() {
10
g := grav.New()
11
12
// connect a pod and set it to reply to any message that it receives
13
p1 := g.Connect()
14
p1.On(func(msg grav.Message) error {
15
data := string(msg.Data())
16
17
reply := grav.NewMsg(grav.MsgTypeDefault, []byte(fmt.Sprintf("hey %s", data)))
18
p1.ReplyTo(msg, reply)
19
20
return nil
21
})
22
23
p2 := g.Connect()
24
msg := grav.NewMsg(grav.MsgTypeDefault, []byte("joey"))
25
26
// send a message and wait for a response
27
p2.Send(msg).WaitOn(func(msg grav.Message) error {
28
fmt.Println("got a reply:", string(msg.Data()))
29
30
return nil
31
})
32
}
33
Copied!
This is an example of Receipts in action. When a message is sent, the MsgReceipt is returned, and then the WaitOn method is used to retrieve a reply from the message stream.
WaitOn will block forever until a reply is received. There is an alternate method WaitUntil that accepts a timeout. Since a receipt is an extension of the Pod that created it, calling any of its methods will replace the receive function for the Pod.
Receipts also have an async method, OnReply. This will run the provided function in the background when a reply is received, and will set the Pod's receive function to nil afterwards.
Last modified 1yr ago
Copy link