veza/veza-backend-api/internal/utils/slug.go
2025-12-03 20:29:37 +01:00

48 lines
1.6 KiB
Go

package utils
import (
"strings"
"unicode"
)
var transliterations = strings.NewReplacer(
"À", "A", "Á", "A", "Â", "A", "Ã", "A", "Ä", "A", "Å", "A", "Æ", "AE",
"Ç", "C", "È", "E", "É", "E", "Ê", "E", "Ë", "E", "Ì", "I", "Í", "I",
"Î", "I", "Ï", "I", "Ð", "D", "Ñ", "N", "Ò", "O", "Ó", "O", "Ô", "O",
"Õ", "O", "Ö", "O", "Ø", "O", "Ù", "U", "Ú", "U", "Û", "U", "Ü", "U",
"Ý", "Y", "Þ", "TH", "ß", "ss", "à", "a", "á", "a", "â", "a", "ã", "a",
"ä", "a", "å", "a", "æ", "ae", "ç", "c", "è", "e", "é", "e", "ê", "e",
"ë", "e", "ì", "i", "í", "i", "î", "i", "ï", "i", "ð", "d", "ñ", "n",
"ò", "o", "ó", "o", "ô", "o", "õ", "o", "ö", "o", "ø", "o", "ù", "u",
"ú", "u", "û", "u", "ü", "u", "ý", "y", "þ", "th", "ÿ", "y",
)
// Slugify converts a string to a URL-friendly slug
// It converts letters to lowercase, replaces spaces and special characters with dashes,
// and removes consecutive dashes and leading/trailing dashes.
// It also transliterates common accented characters to their ASCII equivalents.
func Slugify(s string) string {
// Transliterate common accented characters to their ASCII equivalents
s = transliterations.Replace(s)
var result strings.Builder
result.Grow(len(s))
for _, r := range s {
if unicode.IsLetter(r) || unicode.IsNumber(r) {
result.WriteRune(unicode.ToLower(r))
} else if r == ' ' || r == '-' || r == '_' {
result.WriteRune('-')
}
}
slug := result.String()
// Remove consecutive dashes
for strings.Contains(slug, "--") {
slug = strings.ReplaceAll(slug, "--", "-")
}
// Remove leading/trailing dashes
slug = strings.Trim(slug, "-")
return slug
}