here is my sub.go example:
package main
import (
"fmt"
nats "github.com/nats-io/nats.go"
)
type Message struct {
Status string `json:"Status"`
Msg string `json:"Msg"`
}
type Response struct {
Status string `json:"Status"`
Msg string `json:"Msg"`
}
var nc *nats.Conn
var c *nats.EncodedConn
func start(){
nc, _ := nats.Connect("127.0.0.1:4222")
c, _ := nats.NewEncodedConn(nc, nats.JSON_ENCODER)
c.QueueSubscribe("subject_toto", "queue_titi", func(_, reply string, message *Message) {
fmt.Printf("%+v\n", message)
var response Response
response.Msg = "message received"
response.Status = "Ok"
c.Publish("reply", response)
c.Flush()
})
c.Flush()
}
func main() {
fmt.Println("begin")
go start()
defer c.Close()
fmt.Scanln()
nc.Drain()
// Close connection
nc.Close()
fmt.Println("done")
}
And it runs perfectly, so now I woud like to publish a message to this queue, here is my pub.go:
package main
import (
"fmt"
nats "github.com/nats-io/nats.go"
"time"
)
type Message struct {
Status string `json:"Status"`
Msg string `json:"Msg"`
}
type Response struct {
Status string `json:"Status"`
Msg string `json:"Msg"`
}
var nc *nats.Conn
var c *nats.EncodedConn
func start(){
var err error
var message Message
var response Response
nc, _ := nats.Connect("127.0.0.1:4222")
c, _ := nats.NewEncodedConn(nc, nats.JSON_ENCODER)
message.Status = "Ok"
message.Msg = "hello"
err = c.Request("subject_toto", message, &response, 6*time.Second)
if err != nil {
fmt.Printf("%+v\n", err)
}
fmt.Printf("%+v\n","response")
fmt.Printf("%+v\n", response)
defer c.Close()
}
func main() {
fmt.Println("begin")
start()
fmt.Println("done")
}
But when I try to publish to it I have an empty response:
response {Status: Msg:}
One of the beginning of an answer seems to use PublishRequest but it seems to I can send only string to the server and not a struct.
The problem is with this line:
c.Publish("reply", response)
When you send a request and your subscriber is going to respond, there should be a "reply-to subject" that is called inbox. This inbox is set in the reply
arg of handler function.
So you have to publish your response into the subject that is returned by the reply
arg of the handler function in QueueSubscribe()
, so change that line into:
c.Publish(reply, response)
The value of reply arg is important for communication and is something like this: _INBOX.bw5EtJShBTI9OQdvxFOBlz.VxsGBcjH