| 1 |
package main |
| 2 |
|
| 3 |
import ( |
| 4 |
"fmt" |
| 5 |
"time" |
| 6 |
|
| 7 |
"github.com/nats-io/nats.go" |
| 8 |
) |
| 9 |
|
| 10 |
func main() { |
| 11 |
nc, _ := nats.Connect(nats.DefaultURL) |
| 12 |
defer nc.Close() |
| 13 |
|
| 14 |
// NATS-DOC-START |
| 15 |
// Header Aware service |
| 16 |
nc.Subscribe("service", func(msg *nats.Msg) { |
| 17 |
responseMsg := nats.NewMsg(msg.Reply) |
| 18 |
responseMsg.Data = msg.Data |
| 19 |
responseMsg.Header.Add("X-Response-ID", "123") |
| 20 |
responseMsg.Header.Add("X-Request-ID", msg.Header.Get("X-Request-ID")) |
| 21 |
responseMsg.Header.Add("X-Priority", msg.Header.Get("X-Priority")) |
| 22 |
nc.PublishMsg(responseMsg) |
| 23 |
}) |
| 24 |
|
| 25 |
// Create message with headers |
| 26 |
msg := nats.NewMsg("service") |
| 27 |
msg.Header.Add("X-Request-ID", "123") |
| 28 |
msg.Header.Add("X-Priority", "high") |
| 29 |
msg.Data = []byte("data") |
| 30 |
|
| 31 |
// Send request with headers |
| 32 |
response, err := nc.RequestMsg(msg, time.Second) |
| 33 |
if err == nil { |
| 34 |
fmt.Printf("Response: %s\n", response.Data) |
| 35 |
fmt.Printf("Response ID: %s\n", response.Header.Get("X-Response-ID")) |
| 36 |
} else { |
| 37 |
fmt.Printf("Error: %s\n", err) |
| 38 |
} |
| 39 |
// NATS-DOC-END |
| 40 |
time.Sleep(100 * time.Millisecond) |
| 41 |
} |