2021-08-30 16:48:57 +02:00
|
|
|
package call
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"strings"
|
|
|
|
|
2021-11-01 09:00:14 +00:00
|
|
|
"github.com/urfave/cli/v2"
|
2021-10-12 12:55:53 +01:00
|
|
|
"go-micro.dev/v4"
|
|
|
|
"go-micro.dev/v4/client"
|
2021-11-01 14:34:09 +00:00
|
|
|
mcli "go-micro.dev/v4/cmd/micro/cli"
|
2021-08-30 16:48:57 +02:00
|
|
|
)
|
|
|
|
|
2021-09-06 15:12:27 +02:00
|
|
|
func init() {
|
2021-11-01 14:34:09 +00:00
|
|
|
mcli.Register(&cli.Command{
|
2021-08-30 16:48:57 +02:00
|
|
|
Name: "call",
|
2021-11-01 14:34:09 +00:00
|
|
|
Usage: "Call a service, e.g. " + mcli.App().Name + " call helloworld Helloworld.Call '{\"name\": \"John\"}'",
|
2021-08-30 16:48:57 +02:00
|
|
|
Action: RunCall,
|
2021-09-06 15:12:27 +02:00
|
|
|
})
|
2021-08-30 16:48:57 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// RunCall calls a service endpoint and prints its response. Exits on error.
|
|
|
|
func RunCall(ctx *cli.Context) error {
|
|
|
|
args := ctx.Args().Slice()
|
|
|
|
if len(args) < 2 {
|
|
|
|
return cli.ShowSubcommandHelp(ctx)
|
|
|
|
}
|
|
|
|
|
|
|
|
service := args[0]
|
|
|
|
endpoint := args[1]
|
|
|
|
req := strings.Join(args[2:], " ")
|
|
|
|
if len(req) == 0 {
|
|
|
|
req = `{}`
|
|
|
|
}
|
|
|
|
|
|
|
|
d := json.NewDecoder(strings.NewReader(req))
|
|
|
|
d.UseNumber()
|
|
|
|
|
|
|
|
var creq map[string]interface{}
|
|
|
|
if err := d.Decode(&creq); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
srv := micro.NewService()
|
|
|
|
srv.Init()
|
|
|
|
c := srv.Client()
|
|
|
|
|
|
|
|
request := c.NewRequest(service, endpoint, creq, client.WithContentType("application/json"))
|
2021-09-08 09:30:53 +02:00
|
|
|
var response map[string]interface{}
|
2021-08-30 16:48:57 +02:00
|
|
|
|
|
|
|
if err := c.Call(context.Background(), request, &response); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
b, err := json.Marshal(response)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
fmt.Println(string(b))
|
|
|
|
return nil
|
|
|
|
}
|