aboutsummaryrefslogtreecommitdiff
path: root/example.go
blob: b51bc243214b560376dcfa1bb7d8773245bb34db (plain)
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
package main

import (
	"encoding/json"
	"math/rand/v2"
	"os"
	"time"

	rpc "github.com/karyontech/karyon-go/jsonrpc/client"
	log "github.com/sirupsen/logrus"
)

type Pong struct{}

func runNewClient() error {
	config := rpc.RPCClientConfig{
		Addr: "ws://127.0.0.1:6000",
	}

	client, err := rpc.NewRPCClient(config)
	if err != nil {
		return err
	}
	defer client.Close()

	subID, ch, err := client.Subscribe("Calc.log_subscribe", nil)
	if err != nil {
		return err
	}
	log.Infof("Subscribed successfully: %d\n", subID)

	go func() {
		for notification := range ch {
			log.Infof("Receive new notification: %s\n", notification)
		}
	}()

	for {
		millisecond := rand.IntN(2000-500) + 500
		time.Sleep(time.Duration(millisecond) * time.Millisecond)
		result, err := client.Call("Calc.ping", nil)
		if err != nil {
			return err
		}

		pongMsg := Pong{}
		err = json.Unmarshal(*result, &pongMsg)
		if err != nil {
			return err
		}
	}

}

func main() {
	lvl, ok := os.LookupEnv("LOG_LEVEL")
	if !ok {
		lvl = "debug"
	}
	ll, err := log.ParseLevel(lvl)
	if err != nil {
		ll = log.DebugLevel
	}
	log.SetLevel(ll)

	err = runNewClient()
	if err != nil {
		log.Fatal(err)
	}
}