...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package k8s
16
17 import (
18 "fmt"
19 "regexp"
20 "strings"
21 "unicode"
22 )
23
24 const maxSubdomainLength = 253
25
26 var notLegalRegex = regexp.MustCompile("[^a-z0-9\\-\\.]+")
27
28 func ValueToDNSSubdomainName(value string) string {
29
30
31
32
33
34
35 value = strings.ToLower(value)
36 value = replaceIllegalPunctuation(value)
37 value = toAlphaNumeric(value)
38 value = ensureFirstAndLastCharactersAreAlphaNumeric(value)
39 if len(value) > maxSubdomainLength {
40 value = value[0:maxSubdomainLength]
41 }
42 return value
43 }
44
45 func replaceIllegalPunctuation(value string) string {
46 sb := strings.Builder{}
47 for _, runeValue := range value {
48 if unicode.IsPunct(runeValue) {
49 if !isLegalPunctuation(runeValue) {
50 runeValue = '-'
51 }
52 }
53 sb.WriteRune(runeValue)
54 }
55 return sb.String()
56 }
57
58 func isLegalPunctuation(r rune) bool {
59 return r == '-' || r == '.'
60 }
61
62 func toAlphaNumeric(value string) string {
63 return notLegalRegex.ReplaceAllString(value, "")
64 }
65
66 func ensureFirstAndLastCharactersAreAlphaNumeric(value string) string {
67 defaultCharValue := "a"
68 if value == "" {
69 return defaultCharValue
70 }
71 runes := []rune(value)
72 if !isAlphaNumeric(runes[0]) {
73 value = fmt.Sprintf("%v%v", defaultCharValue, value)
74 }
75 if !isAlphaNumeric(runes[len(runes)-1]) {
76 value = fmt.Sprintf("%v%v", value, defaultCharValue)
77 }
78 return value
79 }
80
81 func isAlphaNumeric(r rune) bool {
82 return unicode.IsLetter(r) || unicode.IsNumber(r)
83 }
84
View as plain text