github.com/ronaksoft/rony@v0.16.26-0.20230807065236-1743dbfe6959/example/echo/cmd/cli-echo/cmd_client.go (about)

     1  package main
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"os"
     7  
     8  	"go.opentelemetry.io/otel/trace"
     9  
    10  	"github.com/ronaksoft/rony"
    11  	"github.com/ronaksoft/rony/config"
    12  	"github.com/ronaksoft/rony/edgec"
    13  	"github.com/ronaksoft/rony/errors"
    14  	service "github.com/ronaksoft/rony/example/echo/rpc"
    15  	"github.com/ronaksoft/rony/registry"
    16  	"github.com/ronaksoft/rony/tools/cliutil"
    17  	"github.com/spf13/cobra"
    18  )
    19  
    20  var ClientCmd = &cobra.Command{
    21  	Use: "client",
    22  	RunE: func(cmd *cobra.Command, args []string) error {
    23  		err := config.BindCmdFlags(cmd)
    24  		if err != nil {
    25  			return errors.WrapText("bind flag:")(err)
    26  		}
    27  
    28  		var tr trace.Tracer
    29  		if tp := initTracer(); tp != nil {
    30  			defer func() {
    31  				tp.Shutdown(context.Background())
    32  			}()
    33  			tr = tp.Tracer("SampleEchoCli")
    34  		}
    35  
    36  		// Sample code for creating a client
    37  		// Instantiate a websocket connection, to use http connection we could use edgec.NewHttp
    38  		wsc := edgec.NewWebsocket(
    39  			edgec.WebsocketConfig{
    40  				Tracer:       tr,
    41  				SeedHostPort: fmt.Sprintf("%s:%d", config.GetString("host"), config.GetInt("port")),
    42  				Handler: func(m *rony.MessageEnvelope) {
    43  					fmt.Println(m.RequestID, registry.C(m.Constructor))
    44  				},
    45  			},
    46  		)
    47  
    48  		// Start the websocket connection manager
    49  		err = wsc.Start()
    50  		if err != nil {
    51  			return errors.WrapText("websocket client:")(err)
    52  		}
    53  
    54  		// Instantiate the client stub code and set its underlying client connection
    55  		service.RegisterSampleCli(&service.SampleCli{}, wsc, ShellCmd)
    56  
    57  		ShellCmd.AddCommand(ExitCmd)
    58  		cliutil.RunShell(ShellCmd)
    59  
    60  		return nil
    61  	},
    62  }
    63  
    64  var ShellCmd = &cobra.Command{}
    65  
    66  var ExitCmd = &cobra.Command{
    67  	Use: "exit",
    68  	Run: func(cmd *cobra.Command, args []string) {
    69  		os.Exit(0)
    70  	},
    71  }