github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/wsctl/cmd/applet/create.go (about) 1 package applet 2 3 import ( 4 "bytes" 5 "fmt" 6 "io" 7 "mime/multipart" 8 "net/http" 9 "os" 10 "path/filepath" 11 12 "github.com/pkg/errors" 13 "github.com/spf13/cobra" 14 "golang.org/x/text/cases" 15 "golang.org/x/text/language" 16 17 "github.com/machinefi/w3bstream/pkg/wsctl/client" 18 "github.com/machinefi/w3bstream/pkg/wsctl/cmd/utils" 19 "github.com/machinefi/w3bstream/pkg/wsctl/config" 20 ) 21 22 var ( 23 _appletCreateUse = map[config.Language]string{ 24 config.English: "create PROJECT_ID FILE INFO", 25 config.Chinese: "create PROJECT_ID FILE INFO", 26 } 27 _appletCreateCmdShorts = map[config.Language]string{ 28 config.English: "Create a applet", 29 config.Chinese: "通过 PROJECT_ID, FILE, INFO 创建 APPLET", 30 } 31 ) 32 33 // newAppletCreateCmd is a command to create applet 34 func newAppletCreateCmd(client client.Client) *cobra.Command { 35 return &cobra.Command{ 36 Use: client.SelectTranslation(_appletCreateUse), 37 Short: client.SelectTranslation(_appletCreateCmdShorts), 38 Args: func(cmd *cobra.Command, args []string) error { 39 if len(args) != 3 { 40 return fmt.Errorf("accepts 3 arg(s), received %d", len(args)) 41 } 42 return nil 43 }, 44 RunE: func(cmd *cobra.Command, args []string) error { 45 cmd.SilenceUsage = true 46 if err := create(cmd, client, args); err != nil { 47 return errors.Wrap(err, fmt.Sprintf("problem create applet %+v", args)) 48 } 49 cmd.Println(cases.Title(language.Und).String(args[0]) + " applet created successfully ") 50 return nil 51 }, 52 } 53 } 54 55 func create(cmd *cobra.Command, client client.Client, args []string) error { 56 createURL := GetAppletCmdUrl(client.Config().Endpoint, args[0]) 57 body, err := loadFile(args[1], args[2]) 58 if err != nil { 59 return err 60 } 61 req, err := http.NewRequest("POST", createURL, body) 62 if err != nil { 63 return errors.Wrap(err, "failed to create applet request") 64 } 65 req.Header.Set("Content-Type", "application/json") 66 67 resp, err := client.Call(createURL, req) 68 if err != nil { 69 return errors.Wrap(err, "failed to create applet") 70 } 71 return utils.PrintResponse(cmd, resp) 72 } 73 74 func loadFile(filePath string, info string) (io.Reader, error) { 75 file, err := os.Open(filePath) 76 if err != nil { 77 return nil, err 78 } 79 defer file.Close() 80 81 body := &bytes.Buffer{} 82 writer := multipart.NewWriter(body) 83 part, err := writer.CreateFormFile("file", filepath.Base(file.Name())) 84 if err != nil { 85 return nil, err 86 } 87 if _, err = io.Copy(part, file); err != nil { 88 return nil, err 89 } 90 91 if err := writer.WriteField("info", info); err != nil { 92 return nil, err 93 } 94 95 if err := writer.Close(); err != nil { 96 return nil, err 97 } 98 99 return body, nil 100 }