grafana/pkg/util/ip_address.go
Sofia Papagiannaki 886bad2fd5
Util: Modify SplitHostPortDefault not to return an error for empty input (#20351)
* Util: Optionally allow empty input in SplitHostPortDefault

Due to a recent change the SQL Server tests failed because passing an
empty datasource url in `util.SplitHostPortDefault` was no more allowed.
This fix contains the following modifications:
- Modifies the util.SplitHostPortDefault not to return an error for empty input.
- Modifies the util.SplitHostPort to return an error for empty input.
- Introduces an additional test for empty input.
2019-11-18 10:42:51 +02:00

90 lines
2.0 KiB
Go

package util
import (
"fmt"
"net"
"strings"
"github.com/grafana/grafana/pkg/util/errutil"
)
// ParseIPAddress parses an IP address and removes port and/or IPV6 format
func ParseIPAddress(input string) (string, error) {
addr, err := SplitHostPort(input)
if err != nil {
return "", errutil.Wrapf(err, "Failed to split network address '%s' by host and port",
input)
}
ip := net.ParseIP(addr.Host)
if ip == nil {
return addr.Host, nil
}
if ip.IsLoopback() {
if strings.Contains(addr.Host, ":") {
// IPv6
return "::1", nil
}
return "127.0.0.1", nil
}
return ip.String(), nil
}
type NetworkAddress struct {
Host string
Port string
}
// SplitHostPortDefault splits ip address/hostname string by host and port. Defaults used if no match found
func SplitHostPortDefault(input, defaultHost, defaultPort string) (NetworkAddress, error) {
addr := NetworkAddress{
Host: defaultHost,
Port: defaultPort,
}
if len(input) == 0 {
return addr, nil
}
start := 0
// Determine if IPv6 address, in which case IP address will be enclosed in square brackets
if strings.Index(input, "[") == 0 {
addrEnd := strings.LastIndex(input, "]")
if addrEnd < 0 {
// Malformed address
return addr, fmt.Errorf("Malformed IPv6 address: '%s'", input)
}
start = addrEnd
}
if strings.LastIndex(input[start:], ":") < 0 {
// There's no port section of the input
// It's still useful to call net.SplitHostPort though, since it removes IPv6
// square brackets from the address
input = fmt.Sprintf("%s:%s", input, defaultPort)
}
host, port, err := net.SplitHostPort(input)
if err != nil {
return addr, errutil.Wrapf(err, "net.SplitHostPort failed for '%s'", input)
}
if len(host) > 0 {
addr.Host = host
}
if len(port) > 0 {
addr.Port = port
}
return addr, nil
}
// SplitHostPort splits ip address/hostname string by host and port
func SplitHostPort(input string) (NetworkAddress, error) {
if len(input) == 0 {
return NetworkAddress{}, fmt.Errorf("Input is empty")
}
return SplitHostPortDefault(input, "", "")
}