Debian Codegraph @

examples/docs/request-reply-calculator/main.go

raw
1 package main
2
3 import (
4 "fmt"
5 "strconv"
6 "strings"
7 "time"
8
9 "github.com/nats-io/nats.go"
10 )
11
12 func main() {
13 nc, _ := nats.Connect(nats.DefaultURL)
14 defer nc.Close()
15
16 // NATS-DOC-START
17 // Calculator service
18 nc.Subscribe("calc.add", func(msg *nats.Msg) {
19 parts := strings.Fields(string(msg.Data))
20 if len(parts) == 2 {
21 a, _ := strconv.Atoi(parts[0])
22 b, _ := strconv.Atoi(parts[1])
23 result := fmt.Sprintf("%d", a+b)
24 msg.Respond([]byte(result))
25 }
26 })
27
28 // Make calculations
29 time.Sleep(100 * time.Millisecond)
30
31 resp, _ := nc.Request("calc.add", []byte("5 3"), time.Second)
32 fmt.Printf("5 + 3 = %s\n", string(resp.Data))
33
34 resp, _ = nc.Request("calc.add", []byte("10 7"), time.Second)
35 fmt.Printf("10 + 7 = %s\n", string(resp.Data))
36 // NATS-DOC-END
37
38 time.Sleep(100 * time.Millisecond)
39 }