mirror of
https://github.com/grafana/grafana.git
synced 2025-02-25 18:55:37 -06:00
utils
This commit is contained in:
parent
d907b1ec6b
commit
e08f61059b
@ -101,3 +101,11 @@ func DecodeBasicAuthHeader(header string) (string, string, error) {
|
|||||||
|
|
||||||
return userAndPass[0], userAndPass[1], nil
|
return userAndPass[0], userAndPass[1], nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func RandomHex(n int) (string, error) {
|
||||||
|
bytes := make([]byte, n)
|
||||||
|
if _, err := rand.Read(bytes); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return hex.EncodeToString(bytes), nil
|
||||||
|
}
|
||||||
|
27
pkg/util/ip_address.go
Normal file
27
pkg/util/ip_address.go
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
package util
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ParseIPAddress parses an IP address and removes port and/or IPV6 format
|
||||||
|
func ParseIPAddress(input string) string {
|
||||||
|
var s string
|
||||||
|
lastIndex := strings.LastIndex(input, ":")
|
||||||
|
|
||||||
|
if lastIndex != -1 {
|
||||||
|
s = input[:lastIndex]
|
||||||
|
}
|
||||||
|
|
||||||
|
s = strings.Replace(s, "[", "", -1)
|
||||||
|
s = strings.Replace(s, "]", "", -1)
|
||||||
|
|
||||||
|
ip := net.ParseIP(s)
|
||||||
|
|
||||||
|
if ip.IsLoopback() {
|
||||||
|
return "127.0.0.1"
|
||||||
|
}
|
||||||
|
|
||||||
|
return ip.String()
|
||||||
|
}
|
14
pkg/util/ip_address_test.go
Normal file
14
pkg/util/ip_address_test.go
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
package util
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
. "github.com/smartystreets/goconvey/convey"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestParseIPAddress(t *testing.T) {
|
||||||
|
Convey("Test parse ip address", t, func() {
|
||||||
|
So(ParseIPAddress("192.168.0.140:456"), ShouldEqual, "192.168.0.140")
|
||||||
|
So(ParseIPAddress("[::1:456]"), ShouldEqual, "127.0.0.1")
|
||||||
|
})
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user