wg-portal/internal/common/util.go

87 lines
1.9 KiB
Go
Raw Permalink Normal View History

2020-11-05 13:37:51 -05:00
package common
2020-11-07 12:36:23 -05:00
import (
2020-11-10 16:23:05 -05:00
"fmt"
2020-11-07 12:36:23 -05:00
"net"
"strings"
)
2020-11-05 13:37:51 -05:00
// BroadcastAddr returns the last address in the given network, or the broadcast address.
func BroadcastAddr(n *net.IPNet) net.IP {
// The golang net package doesn't make it easy to calculate the broadcast address. :(
var broadcast net.IP
if len(n.IP) == 4 {
broadcast = net.ParseIP("0.0.0.0").To4()
} else {
broadcast = net.ParseIP("::")
}
for i := 0; i < len(n.IP); i++ {
broadcast[i] = n.IP[i] | ^n.Mask[i]
}
return broadcast
}
// http://play.golang.org/p/m8TNTtygK0
func IncreaseIP(ip net.IP) {
for j := len(ip) - 1; j >= 0; j-- {
ip[j]++
if ip[j] > 0 {
break
}
}
}
// IsIPv6 check if given ip is IPv6
func IsIPv6(address string) bool {
ip := net.ParseIP(address)
if ip == nil {
return false
}
return ip.To4() == nil
}
2020-11-07 12:36:23 -05:00
2021-02-26 16:17:04 -05:00
// ParseStringList converts a comma separated string into a list of strings.
// It also trims spaces from each element of the list.
2020-11-08 04:26:18 -05:00
func ParseStringList(lst string) []string {
tokens := strings.Split(lst, ",")
validatedTokens := make([]string, 0, len(tokens))
for i := range tokens {
tokens[i] = strings.TrimSpace(tokens[i])
if tokens[i] != "" {
validatedTokens = append(validatedTokens, tokens[i])
2020-11-07 12:36:23 -05:00
}
}
2020-11-08 04:26:18 -05:00
return validatedTokens
2020-11-07 12:36:23 -05:00
}
2021-02-26 16:17:04 -05:00
// ListToString converts a list of strings into a comma separated string.
2020-11-08 04:26:18 -05:00
func ListToString(lst []string) string {
2020-11-07 12:36:23 -05:00
return strings.Join(lst, ", ")
}
2020-11-10 16:23:05 -05:00
// ListContains checks if a needle exists in the given list.
func ListContains(lst []string, needle string) bool {
for _, entry := range lst {
if entry == needle {
return true
}
}
return false
}
2020-11-10 16:23:05 -05:00
// https://yourbasic.org/golang/formatting-byte-size-to-human-readable-format/
func ByteCountSI(b int64) string {
const unit = 1000
if b < unit {
return fmt.Sprintf("%d B", b)
}
div, exp := int64(unit), 0
for n := b / unit; n >= unit; n /= unit {
div *= unit
exp++
}
return fmt.Sprintf("%.1f %cB",
float64(b)/float64(div), "kMGTPE"[exp])
}