github.com/fastly/cli@v1.7.2-0.20240304164155-9d0f1d77c3bf/pkg/commands/tls/custom/privatekey/create.go (about)

     1  package privatekey
     2  
     3  import (
     4  	"io"
     5  
     6  	"github.com/fastly/go-fastly/v9/fastly"
     7  
     8  	"github.com/fastly/cli/pkg/argparser"
     9  	"github.com/fastly/cli/pkg/global"
    10  	"github.com/fastly/cli/pkg/text"
    11  )
    12  
    13  // NewCreateCommand returns a usable command registered under the parent.
    14  func NewCreateCommand(parent argparser.Registerer, g *global.Data) *CreateCommand {
    15  	var c CreateCommand
    16  	c.CmdClause = parent.Command("create", "Create a TLS private key").Alias("add")
    17  	c.Globals = g
    18  
    19  	// Required.
    20  	c.CmdClause.Flag("key", "The contents of the private key. Must be a PEM-formatted key").Required().StringVar(&c.key)
    21  	c.CmdClause.Flag("name", "A customizable name for your private key").Required().StringVar(&c.name)
    22  
    23  	return &c
    24  }
    25  
    26  // CreateCommand calls the Fastly API to create an appropriate resource.
    27  type CreateCommand struct {
    28  	argparser.Base
    29  
    30  	key  string
    31  	name string
    32  }
    33  
    34  // Exec invokes the application logic for the command.
    35  func (c *CreateCommand) Exec(_ io.Reader, out io.Writer) error {
    36  	input := c.constructInput()
    37  
    38  	r, err := c.Globals.APIClient.CreatePrivateKey(input)
    39  	if err != nil {
    40  		c.Globals.ErrLog.AddWithContext(err, map[string]any{
    41  			"Private Key Name": c.name,
    42  		})
    43  		return err
    44  	}
    45  
    46  	text.Success(out, "Created TLS Private Key '%s'", r.Name)
    47  	return nil
    48  }
    49  
    50  // constructInput transforms values parsed from CLI flags into an object to be used by the API client library.
    51  func (c *CreateCommand) constructInput() *fastly.CreatePrivateKeyInput {
    52  	var input fastly.CreatePrivateKeyInput
    53  
    54  	input.Key = c.key
    55  	input.Name = c.name
    56  
    57  	return &input
    58  }