wasmcloud/cmd/wasmcloud/handler_invoke.go

77 lines
1.6 KiB
Go

package main
import (
"bytes"
"context"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"github.com/google/subcommands"
)
type handlerInvokeCmd struct {
fin string
}
func (hic *handlerInvokeCmd) SetFlags(fs *flag.FlagSet) {
fs.StringVar(&hic.fin, "i", "", "input file to pipe to wasmcloud")
}
func (handlerInvokeCmd) Name() string { return "invoke" }
func (handlerInvokeCmd) Synopsis() string { return "synchronously invoke a handler on wasmcloud" }
func (handlerInvokeCmd) Usage() string {
return `wasmcloud invoke <name>
$ wasmcloud invoke princess-of-wands-4018
Invokes a given handler with input read from the given file. Use /dev/stdin
if you want to pipe things.
Flags:
`
}
func (hic handlerInvokeCmd) Execute(ctx context.Context, fs *flag.FlagSet, _ ...interface{}) subcommands.ExitStatus {
if fs.NArg() != 1 {
fmt.Println("usage: wasmcloud invoke <handler-name>")
return subcommands.ExitUsageError
}
hname := fs.Arg(0)
var buf = bytes.NewBuffer(nil)
if hic.fin != "" {
data, err := ioutil.ReadFile(hic.fin)
if err != nil {
log.Fatal(err)
}
buf = bytes.NewBuffer(data)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, *apiServer+"/invoke/sync?name="+hname+"&whole-bundle=true", buf)
if err != nil {
log.Fatal(err)
}
withAPI(req)
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
io.Copy(os.Stdout, resp.Body)
return subcommands.ExitFailure
}
io.Copy(os.Stdout, resp.Body)
return subcommands.ExitSuccess
}