github.com/justincormack/cli@v0.0.0-20201215022714-831ebeae9675/cli/command/container/port.go (about)

     1  package container
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"strings"
     7  
     8  	"github.com/docker/cli/cli"
     9  	"github.com/docker/cli/cli/command"
    10  	"github.com/docker/go-connections/nat"
    11  	"github.com/pkg/errors"
    12  	"github.com/spf13/cobra"
    13  )
    14  
    15  type portOptions struct {
    16  	container string
    17  
    18  	port string
    19  }
    20  
    21  // NewPortCommand creates a new cobra.Command for `docker port`
    22  func NewPortCommand(dockerCli command.Cli) *cobra.Command {
    23  	var opts portOptions
    24  
    25  	cmd := &cobra.Command{
    26  		Use:   "port CONTAINER [PRIVATE_PORT[/PROTO]]",
    27  		Short: "List port mappings or a specific mapping for the container",
    28  		Args:  cli.RequiresRangeArgs(1, 2),
    29  		RunE: func(cmd *cobra.Command, args []string) error {
    30  			opts.container = args[0]
    31  			if len(args) > 1 {
    32  				opts.port = args[1]
    33  			}
    34  			return runPort(dockerCli, &opts)
    35  		},
    36  	}
    37  	return cmd
    38  }
    39  
    40  func runPort(dockerCli command.Cli, opts *portOptions) error {
    41  	ctx := context.Background()
    42  
    43  	c, err := dockerCli.Client().ContainerInspect(ctx, opts.container)
    44  	if err != nil {
    45  		return err
    46  	}
    47  
    48  	if opts.port != "" {
    49  		port := opts.port
    50  		proto := "tcp"
    51  		parts := strings.SplitN(port, "/", 2)
    52  
    53  		if len(parts) == 2 && len(parts[1]) != 0 {
    54  			port = parts[0]
    55  			proto = parts[1]
    56  		}
    57  		natPort := port + "/" + proto
    58  		newP, err := nat.NewPort(proto, port)
    59  		if err != nil {
    60  			return err
    61  		}
    62  		if frontends, exists := c.NetworkSettings.Ports[newP]; exists && frontends != nil {
    63  			for _, frontend := range frontends {
    64  				fmt.Fprintf(dockerCli.Out(), "%s:%s\n", frontend.HostIP, frontend.HostPort)
    65  			}
    66  			return nil
    67  		}
    68  		return errors.Errorf("Error: No public port '%s' published for %s", natPort, opts.container)
    69  	}
    70  
    71  	for from, frontends := range c.NetworkSettings.Ports {
    72  		for _, frontend := range frontends {
    73  			fmt.Fprintf(dockerCli.Out(), "%s -> %s:%s\n", from, frontend.HostIP, frontend.HostPort)
    74  		}
    75  	}
    76  
    77  	return nil
    78  }