github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/wsctl/cmd/instance/stop.go (about)

     1  package instance
     2  
     3  import (
     4  	"fmt"
     5  	"net/http"
     6  
     7  	"github.com/pkg/errors"
     8  	"github.com/spf13/cobra"
     9  	"golang.org/x/text/cases"
    10  	"golang.org/x/text/language"
    11  
    12  	"github.com/machinefi/w3bstream/pkg/wsctl/client"
    13  	"github.com/machinefi/w3bstream/pkg/wsctl/cmd/utils"
    14  	"github.com/machinefi/w3bstream/pkg/wsctl/config"
    15  )
    16  
    17  var (
    18  	_instanceStopUse = map[config.Language]string{
    19  		config.English: "stop INSTANCE_ID",
    20  		config.Chinese: "stop INSTANCE_ID",
    21  	}
    22  	_instanceStopCmdShorts = map[config.Language]string{
    23  		config.English: "Stop a instance",
    24  		config.Chinese: "通过 INSTANCE_ID 停止 INSTANCE",
    25  	}
    26  )
    27  
    28  // newInstanceStopCmd is a command to stop instance
    29  func newInstanceStopCmd(client client.Client) *cobra.Command {
    30  	return &cobra.Command{
    31  		Use:   client.SelectTranslation(_instanceStopUse),
    32  		Short: client.SelectTranslation(_instanceStopCmdShorts),
    33  		Args: func(cmd *cobra.Command, args []string) error {
    34  			if len(args) != 1 {
    35  				return fmt.Errorf("accepts 1 arg(s), received %d", len(args))
    36  			}
    37  			return nil
    38  		},
    39  		RunE: func(cmd *cobra.Command, args []string) error {
    40  			cmd.SilenceUsage = true
    41  			if err := stop(cmd, client, args); err != nil {
    42  				return errors.Wrap(err, fmt.Sprintf("problem stop instance %+v", args))
    43  			}
    44  			cmd.Println(cases.Title(language.Und).String(args[0]) + " instance stopped successfully ")
    45  			return nil
    46  		},
    47  	}
    48  }
    49  
    50  func stop(cmd *cobra.Command, client client.Client, args []string) error {
    51  	url := GetInstanceCmdUrl(client.Config().Endpoint, args[0], "STOP")
    52  	req, err := http.NewRequest("PUT", url, nil)
    53  	if err != nil {
    54  		return errors.Wrap(err, "failed to stop instance request")
    55  	}
    56  	req.Header.Set("Content-Type", "application/json")
    57  
    58  	resp, err := client.Call(url, req)
    59  	if err != nil {
    60  		return errors.Wrap(err, "failed to stop instance")
    61  	}
    62  	return utils.PrintResponse(cmd, resp)
    63  }