github.com/sleungcy/cli@v7.1.0+incompatible/command/flag/ssh_port_forwarding.go (about) 1 package flag 2 3 import ( 4 "fmt" 5 "regexp" 6 "strings" 7 8 flags "github.com/jessevdk/go-flags" 9 ) 10 11 const DefaultLocalAddress = "localhost" 12 13 type SSHPortForwarding struct { 14 LocalAddress string 15 RemoteAddress string 16 } 17 18 func (s *SSHPortForwarding) UnmarshalFlag(val string) error { 19 splitHosts := strings.Split(val, ":") 20 for _, piece := range splitHosts { 21 if len(piece) == 0 { 22 return &flags.Error{ 23 Type: flags.ErrRequired, 24 Message: fmt.Sprintf("Bad local forwarding specification '%s'", val), 25 } 26 } 27 } 28 29 re := regexp.MustCompile(`^\d+$`) 30 switch { 31 case len(splitHosts) == 3 && re.MatchString(splitHosts[0]) && re.MatchString(splitHosts[2]): 32 s.LocalAddress = fmt.Sprintf("%s:%s", DefaultLocalAddress, splitHosts[0]) 33 s.RemoteAddress = fmt.Sprintf("%s:%s", splitHosts[1], splitHosts[2]) 34 case len(splitHosts) == 4 && re.MatchString(splitHosts[1]) && re.MatchString(splitHosts[3]): 35 s.LocalAddress = fmt.Sprintf("%s:%s", splitHosts[0], splitHosts[1]) 36 s.RemoteAddress = fmt.Sprintf("%s:%s", splitHosts[2], splitHosts[3]) 37 default: 38 return &flags.Error{ 39 Type: flags.ErrRequired, 40 Message: fmt.Sprintf("Bad local forwarding specification '%s'", val), 41 } 42 } 43 44 return nil 45 }