1
0
Fork 0
This repository has been archived on 2025-09-02. You can view files and clone it, but you cannot make any changes to it's state, such as pushing and creating new issues, pull requests or comments.
mareshq-yggdrasil/pkg/slug/slug.go
Vojtech Mares 2d32c80182
feat!: add slug to training
BREAKING CHANGE: update init migration
2024-06-26 22:24:36 +02:00

47 lines
766 B
Go

package slug
import (
"errors"
"github.com/gosimple/unidecode"
"regexp"
"strings"
)
type Slug string
var (
ErrInvalidSlug = errors.New("invalid slug")
regexpNonAuthorizedChars = regexp.MustCompile("[^a-zA-Z0-9-_]")
regexpMultipleDashes = regexp.MustCompile("-+")
)
func New(s string) Slug {
s = unidecode.Unidecode(s)
s = strings.ToLower(s)
s = regexpNonAuthorizedChars.ReplaceAllString(s, "-")
s = regexpMultipleDashes.ReplaceAllString(s, "-")
s = strings.Trim(s, "-_")
return Slug(s)
}
func NewString(s string) string {
return New(s).String()
}
func Validate(s string) error {
if s == "" {
return ErrInvalidSlug
}
if s == NewString(s) {
return nil
}
return ErrInvalidSlug
}
func (s Slug) String() string {
return string(s)
}