英文:
Generated valid label value (Kubernetes)
问题
在Kubernetes中,标签的值需要是有效的。
例如,我从提供者的REST API接收到的输入是Dedicated Server 1U
,我想将其写入一个标签。是否有一种方法可以通过Go从任意字符串生成有效的标签?
英文:
Label values in Kubernetes need to be valid.
For example the input I receive from a rest-API of a provider, which I want to write to a label: Dedicated Server 1U
.
Is there a way to generate a valid label via Go from an arbitrary string?
答案1
得分: 2
你可以编写一个函数来实现这个功能,例如:
func generateLabel(input string) string {
input = strings.Replace(input, " ", "-", -1)
return "api-label=" + input
}
- 这个函数将接收到的字符串中的空格替换为"-"
- 你可以将键更改为任何你喜欢的字符串。
- 你还可以添加一个正则表达式检查,以确保生成的值符合标签的约束条件(这取决于从API接收到的是否有特殊字符)。
如果要接受包含不需要的字符的字符串,请参考以下代码:
package main
import (
"regexp"
"strings"
"fmt"
)
func generateLabel(input string) string {
input = strings.Replace(input, " ", "-", -1)
re := regexp.MustCompile("[^a-zA-Z0-9-]")
input = re.ReplaceAllString(input, "")
re = regexp.MustCompile("^[^a-zA-Z0-9]([-a-zA-Z0-9]*[a-zA-Z0-9])?$")
input = re.ReplaceAllString(input, "")
return "api-label=" + input
}
func main() {
label := generateLabel("Dedicated Server 1U")
fmt.Println(label) // 输出: "api-label=Dedicated-Server-1U"
label1 := generateLabel("Dedicated&test")
fmt.Println(label1) // 输出: "api-label=Dedicatedtest"
label2 := generateLabel("Dedicated,test##&(*!great")
fmt.Println(label2) // 输出: "api-label=Dedicatedtestgreat"
}
希望对你有帮助!
英文:
you can have a function to do this, for example:
func generateLabel(input string) string {
input = strings.Replace(input, " ", "-", -1)
return "api-label=" + input
}
- the function replaces the spaces in the received string to "-"
- you can change the key to any string you like.
- you can also add a regex check to make sure that the generated value complies with the label constraints. (this depends if any special characters are being received from the API)
To accept the string even when there are unwanted characters, check the below:
package main
import (
"regexp"
"strings"
"fmt"
)
func generateLabel(input string) string {
input = strings.Replace(input, " ", "-", -1)
re := regexp.MustCompile("[^a-zA-Z0-9-]")
input = re.ReplaceAllString(input, "")
re = regexp.MustCompile("^[^a-zA-Z0-9]([-a-zA-Z0-9]*[a-zA-Z0-9])?$")
input = re.ReplaceAllString(input, "")
return "api-label=" + input
}
func main() {
label := generateLabel("Dedicated Server 1U")
fmt.Println(label) // Output: "api-label=Dedicated-Server-1U"
label1 := generateLabel("Dedicated&test")
fmt.Println(label1) // Output: "api-label=Dedicatedtest"
label2 := generateLabel("Dedicated,test##&(*!great")
fmt.Println(label2) // Output: "api-label=Dedicatedtestgreat"
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论