97 lines
2.0 KiB
Go
97 lines
2.0 KiB
Go
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"
|
|
)
|
|
|
|
type handlerCreateCmd struct {
|
|
abi string
|
|
}
|
|
|
|
func (handlerCreateCmd) Name() string { return "create" }
|
|
func (handlerCreateCmd) Synopsis() string { return "create a new handler" }
|
|
func (handlerCreateCmd) Usage() string {
|
|
return `wasmcloud create [options] <filename.wasm>
|
|
|
|
$ 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")
|
|
}
|
|
|
|
func (h handlerCreateCmd) Execute(ctx context.Context, fs *flag.FlagSet, _ ...interface{}) subcommands.ExitStatus {
|
|
if fs.NArg() != 1 {
|
|
fmt.Println("usage: wasmcloud create [options] <filename>")
|
|
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,
|
|
}
|
|
|
|
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
|
|
}
|