<p>Label values in Kubernetes need to be valid.</p>
<p>See <a href="https://github.com/kubernetes/apimachinery/blob/bfd2aff97e594f6aad77acbe2cbbe190acc93cbc/pkg/util/validation/validation.go#L167" rel="nofollow noreferrer">IsValidLabelValue()</a></p>
<p>For example the input I receive from a rest-API of a provider, which I want to write to a label: <code>Dedicated Server 1U</code>.</p>
<p>Is there a way to generate a valid label via Go from an arbitrary string?</p>

guettli
<p>you can have a function to do this, for example:</p>
<pre><code>func generateLabel(input string) string {
    input = strings.Replace(input, &quot; &quot;, &quot;-&quot;, -1)
    return &quot;api-label=&quot; + input
}
</code></pre>
<ul>
<li>the function replaces the spaces in the received string to &quot;-&quot;</li>
<li>you can change the key to any string you like.</li>
<li>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)</li>
</ul>
<p>To accept the string even when there are unwanted characters, check the below:</p>
<pre><code>package main

import (
        &quot;regexp&quot;
        &quot;strings&quot;
        &quot;fmt&quot;
)

func generateLabel(input string) string {
    input = strings.Replace(input, &quot; &quot;, &quot;-&quot;, -1)
    re := regexp.MustCompile(&quot;[^a-zA-Z0-9-]&quot;)
    input = re.ReplaceAllString(input, &quot;&quot;)

    re = regexp.MustCompile(&quot;^[^a-zA-Z0-9]([-a-zA-Z0-9]*[a-zA-Z0-9])?$&quot;)
    input = re.ReplaceAllString(input, &quot;&quot;)

    return &quot;api-label=&quot; + input
}

func main() {
    label := generateLabel(&quot;Dedicated Server 1U&quot;)
    fmt.Println(label) // Output: &quot;api-label=Dedicated-Server-1U&quot;

    label1 := generateLabel(&quot;Dedicated&amp;test&quot;)
    fmt.Println(label1) // Output: &quot;api-label=Dedicatedtest&quot;

    label2 := generateLabel(&quot;Dedicated,test##&amp;(*!great&quot;)
    fmt.Println(label2) // Output: &quot;api-label=Dedicatedtestgreat&quot;
}
</code></pre>
