Hostname (Single Label, RFC 1123) in GO
Validate a single-label hostname per RFC 1123: 1–63 chars, letters/digits/hyphens, can't start or end with hyphen.
Try it in the GO tester →Pattern
regexGO
^[a-zA-Z0-9](?:[a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?$Go (RE2) code
goGo
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`^[a-zA-Z0-9](?:[a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?$`)
input := `web-01`
for _, match := range re.FindAllString(input, -1) {
fmt.Println(match)
}
}Uses `regexp.MustCompile` (panics on bad patterns at startup) and `FindAllString` for all matches.
How the pattern works
^[a-zA-Z0-9] requires the first character to be a letter or digit. (?:[a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])? optionally matches up to 61 more characters (letters, digits, hyphens) followed by a letter/digit ending — preventing trailing hyphens. Combined max length: 63 characters per RFC 1123.
Examples
Input
web-01Matches
web-01
Input
host123Matches
host123
Input
-bad-startNo match
—