A 70-line varlinkctl call: invoke any method with JSON parameters, with
-more for streams and -oneway for fire-and-forget. It exercises every call
shape of the core package with json.RawMessage in and out.
// Command raw-call calls any Varlink method with JSON parameters and prints// the replies, like `varlinkctl call`. It shows the core package on its// own: no generated bindings needed.//// go run ./examples/raw-call /run/systemd/io.systemd.Manager io.systemd.Manager.Describe// go run ./examples/raw-call -more /run/systemd/userdb/io.systemd.Multiplexer \// io.systemd.UserDatabase.GetUserRecord '{"service":"io.systemd.Multiplexer"}'packagemainimport("bytes""context""encoding/json""errors""flag""fmt""log""os""github.com/rossedman/sdvarlink/varlink")// main runs the example; see the package comment for usage.funcmain(){more:=flag.Bool("more",false,"request a stream of replies")oneway:=flag.Bool("oneway",false,"send without waiting for a reply")flag.Parse()ifflag.NArg()<2||flag.NArg()>3{log.Fatal("usage: raw-call [-more|-oneway] SOCKET METHOD [JSON]")}socket,method:=flag.Arg(0),flag.Arg(1)params:=json.RawMessage("{}")ifflag.NArg()==3{params=json.RawMessage(flag.Arg(2))}ctx:=context.Background()conn,err:=varlink.Dial(ctx,socket)iferr!=nil{log.Fatal(err)}deferconn.Close()switch{case*oneway:err=conn.Oneway(ctx,method,params)case*more:forr,rerr:=rangeconn.Stream(ctx,method,params){ifrerr!=nil{err=rerrbreak}print(r.Parameters)r.Close()}default:varoutjson.RawMessageiferr=conn.Call(ctx,method,params,&out);err==nil{print(out)}}varve*varlink.Erroriferrors.As(err,&ve){fmt.Fprintf(os.Stderr,"error: %s %s\n",ve.Name,ve.Parameters)os.Exit(1)}iferr!=nil{log.Fatal(err)}}// print writes a reply to stdout, indented when it is valid JSON.funcprint(rawjson.RawMessage){varbufbytes.Bufferifjson.Indent(&buf,raw,""," ")!=nil{buf.Write(raw)}fmt.Println(buf.String())}