package main import ( "bytes" "context" "encoding/json" "flag" "fmt" "io" "io/ioutil" "log" "net/http" "os" "time" "github.com/google/subcommands" "tulpa.dev/within/wasmcloud/cmd/internal" "within.website/olin/policy" ) type handlerCreateCmd struct { abi, policyFile string } func (handlerCreateCmd) Name() string { return "create" } func (handlerCreateCmd) Synopsis() string { return "create a new handler" } func (handlerCreateCmd) Usage() string { return `wasmcloud create [options] $ wasmcloud create filename.wasm $ wasmcloud create -abi dagger filename.wasm Creates a new handler on wasmcloud. Returns a name you can use to invoke the function. Flags: ` } func (h *handlerCreateCmd) SetFlags(fs *flag.FlagSet) { fs.StringVar(&h.abi, "abi", "cwa", "WebAssembly ABI to use for the handler") fs.StringVar(&h.policyFile, "policy", "", "if set, use this policy file for the handler") } func (h handlerCreateCmd) Execute(ctx context.Context, fs *flag.FlagSet, _ ...interface{}) subcommands.ExitStatus { if fs.NArg() != 1 { fmt.Println("usage: wasmcloud create [options] ") return subcommands.ExitUsageError } fname := fs.Arg(0) data, err := ioutil.ReadFile(fname) if err != nil { log.Fatal(err) } hdlr := internal.Handler{ ABI: h.abi, WASM: data, } if h.policyFile != "" { data, err := ioutil.ReadFile(h.policyFile) if err != nil { log.Fatal(err) } pol, err := policy.Parse(h.policyFile, data) if err != nil { log.Fatal(err) } err = internal.ValidatePolicy(pol) if err != nil { log.Fatal(err) } hdlr.Policy = data } bodyData, _ := json.Marshal(hdlr) req, err := http.NewRequestWithContext(ctx, http.MethodPost, *apiServer+"/api/handler/create", bytes.NewBuffer(bodyData)) if err != nil { log.Fatal(err) } withAPI(req) resp, err := http.DefaultClient.Do(req) if err != nil { log.Fatal(err) } if resp.StatusCode != http.StatusOK { io.Copy(os.Stdout, resp.Body) return subcommands.ExitFailure } type apiResp struct { ID int `json:"ID"` CreatedAt time.Time `json:"CreatedAt"` UpdatedAt time.Time `json:"UpdatedAt"` Name string `json:"Name"` Path string `json:"Path"` } var result apiResp err = json.NewDecoder(resp.Body).Decode(&result) resp.Body.Close() if err != nil { log.Fatal(err) } fmt.Println("created new handler") fmt.Printf("name: %s\nIPFS ID: %s\n", result.Name, result.Path) return subcommands.ExitSuccess }