-
Notifications
You must be signed in to change notification settings - Fork 785
/
k8s.go
33 lines (30 loc) · 1.16 KB
/
k8s.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package util
import (
"fmt"
"strings"
"unicode"
)
// EncodeKubernetesName takes a string and turns it into a form suitable for use as a Kubernetes name.
// Note there is no decode functionality provided atm (and things like escaping escape codes aren't handled), so
// round-tripping is not possible yet.
// K8S names are lower case, numbers, '-', and '.'. Invalid characters are percent-encoded in a _similar_ way to URL
// encoding, with a period ('.') followed by the numerical character code. Conversion is:
// Upper case letters -> lower case.
// 'a-z', '0-9', '-', '.' -> left as-is.
// Any other characters: percent-encoded ('.' + rune hex code).
func EncodeKubernetesName(name string) string {
encodedName := strings.Builder{}
for _, ch := range name {
if ch >= 'a' && ch <= 'z' || ch >= '0' && ch <= '9' || ch == '-' || ch == '.' {
//allowed in name.
encodedName.WriteRune(ch)
} else if ch >= 'A' && ch <= 'Z' {
//Apply toLower encoding.
encodedName.WriteString(fmt.Sprintf(".%c", unicode.ToLower(ch)))
} else {
//Apply character-code encoding.
encodedName.WriteString(fmt.Sprintf(".%X", int(ch)))
}
}
return encodedName.String()
}