| 
 | 1 | +package portformat  | 
 | 2 | + | 
 | 3 | +import (  | 
 | 4 | +	"errors"  | 
 | 5 | +	"strconv"  | 
 | 6 | +	"strings"  | 
 | 7 | +)  | 
 | 8 | + | 
 | 9 | +const (  | 
 | 10 | +	porterrmsg = "Invalid port specification"  | 
 | 11 | +)  | 
 | 12 | + | 
 | 13 | +func dashSplit(sp string, ports *[]int) error {  | 
 | 14 | +	dp := strings.Split(sp, "-")  | 
 | 15 | +	if len(dp) != 2 {  | 
 | 16 | +		return errors.New(porterrmsg)  | 
 | 17 | +	}  | 
 | 18 | +	start, err := strconv.Atoi(dp[0])  | 
 | 19 | +	if err != nil {  | 
 | 20 | +		return errors.New(porterrmsg)  | 
 | 21 | +	}  | 
 | 22 | +	end, err := strconv.Atoi(dp[1])  | 
 | 23 | +	if err != nil {  | 
 | 24 | +		return errors.New(porterrmsg)  | 
 | 25 | +	}  | 
 | 26 | +	if start > end || start < 1 || end > 65535 {  | 
 | 27 | +		return errors.New(porterrmsg)  | 
 | 28 | +	}  | 
 | 29 | +	for ; start <= end; start++ {  | 
 | 30 | +		*ports = append(*ports, start)  | 
 | 31 | +	}  | 
 | 32 | +	return nil  | 
 | 33 | +}  | 
 | 34 | + | 
 | 35 | +func convertAndAddPort(p string, ports *[]int) error {  | 
 | 36 | +	i, err := strconv.Atoi(p)  | 
 | 37 | +	if err != nil {  | 
 | 38 | +		return errors.New(porterrmsg)  | 
 | 39 | +	}  | 
 | 40 | +	if i < 1 || i > 65535 {  | 
 | 41 | +		return errors.New(porterrmsg)  | 
 | 42 | +	}  | 
 | 43 | +	*ports = append(*ports, i)  | 
 | 44 | +	return nil  | 
 | 45 | +}  | 
 | 46 | + | 
 | 47 | +// Parse turns a string of ports separated by '-' or ',' and returns a slice of Ints.  | 
 | 48 | +func Parse(s string) ([]int, error) {  | 
 | 49 | +	ports := []int{}  | 
 | 50 | +	if strings.Contains(s, ",") && strings.Contains(s, "-") {  | 
 | 51 | +		sp := strings.Split(s, ",")  | 
 | 52 | +		for _, p := range sp {  | 
 | 53 | +			if strings.Contains(p, "-") {  | 
 | 54 | +				if err := dashSplit(p, &ports); err != nil {  | 
 | 55 | +					return ports, err  | 
 | 56 | +				}  | 
 | 57 | +			} else {  | 
 | 58 | +				if err := convertAndAddPort(p, &ports); err != nil {  | 
 | 59 | +					return ports, err  | 
 | 60 | +				}  | 
 | 61 | +			}  | 
 | 62 | +		}  | 
 | 63 | +	} else if strings.Contains(s, ",") {  | 
 | 64 | +		sp := strings.Split(s, ",")  | 
 | 65 | +		for _, p := range sp {  | 
 | 66 | +			convertAndAddPort(p, &ports)  | 
 | 67 | +		}  | 
 | 68 | +	} else if strings.Contains(s, "-") {  | 
 | 69 | +		if err := dashSplit(s, &ports); err != nil {  | 
 | 70 | +			return ports, err  | 
 | 71 | +		}  | 
 | 72 | +	} else {  | 
 | 73 | +		if err := convertAndAddPort(s, &ports); err != nil {  | 
 | 74 | +			return ports, err  | 
 | 75 | +		}  | 
 | 76 | +	}  | 
 | 77 | +	return ports, nil  | 
 | 78 | +}  | 
0 commit comments