slugcraft

package module
v1.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 9, 2025 License: MIT Imports: 9 Imported by: 0

README

Slug Craft

Slug Craft

Go version Go report Code coverage
Wiki License Build Status

The ultimate Go package for crafting URL-friendly slugs. Fast, flexible, and built for the real world—SlugCraft handles multilingual text, avoids collisions, and optimizes for SEO and UX like no other.

Why SlugCraft?

  • 🌍 Multilingual Magic: Smart transliteration for non-Latin scripts (e.g., "привет" → "privet").
  • Blazing Fast: Zero-allocation options and bulk processing for scale.
  • 🛠️ Configurable: Build your own slug pipeline with ease.
  • 🚀 Unique Slugs: Collision avoidance with timestamps, UUIDs, or custom suffixes.
  • SEO & UX Ready: Human-readable, meaningful slugs out of the box.

Say goodbye to boring, brittle slug libraries. SlugCraft is here to level up your Go projects.


Package Installation

To use SlugCraft as a library in your Go project, install it with:

go get github.com/mnuddindev/slugcraft@latest

Example

package main

import (
	"context"
	"fmt"
	"github.com/mnuddindev/slugcraft"
)

func main() {
	s := slugcraft.New(
		slugcraft.WithLanguage("bn"),
		slugcraft.WithStopwords("en"),
		slugcraft.WithAbbreviation("বাংলা", "BN"),
	)
	slug, err := s.Make(context.Background(), "বাংলা the World")
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	fmt.Println(slug) // Output: "bn-world"
}

CLI Installation

To install the SlugCraft CLI tool globally on your machine, use:

go install github.com/mnuddindev/slugcraft/cmd/slugcraft@latest

CLI Usage

Generate slugs directly from the command line:

slugcraft -input "বাংলা প্রিয়" -lang=bn

output: bangla-priyo

Available Flags

Available Flags
    -input string: Text to slugify (required)
    -lang string: Language (e.g., bn, ru; optional)
    -cache bool: Enable cache for uniqueness (default: false)
    -suffix string: Suffix style (numeric, version, revision; default: numeric)
    -max int: Maximum slug length (default: 100)
    -stopwords string: Language for stopwords (e.g., en; optional)
    -regex string: Regex filter pattern (e.g., [^a-z0-9-]) (optional)
    -replace string: Regex replacement (default: "")
    -abbr string: Abbreviations (e.g., বাংলা=BN,আমি=ME) (optional)
	-zeroalloc bool: Enable zero allocation method to generate (default: true)
	-file string: Get file name and path to generate slug from file concurrently
    -help: Show usage info

CLI Examples

# English with stopwords and regex
slugcraft -input "Hello the World!" -stopwords=en -regex="[^a-z0-9-]" -replace=""
# Output: hello-world

# Bangla with abbreviations
slugcraft -input "বাংলা আমি" -lang=bn -abbr="বাংলা=BN,আমি=ME"
# Output: bn-me

License

The source files are distributed under the the Massachusetts Institute of Technology, unless otherwise noted.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DefaultStopWords

func DefaultStopWords(lang string) map[string]struct{}

DefaultStopWords returns a basic stopwords map.

func TransliterateBangla

func TransliterateBangla(input string, b *strings.Builder) string

TransliterateBangla converts Bengali text to Banglish.

func TransliterateGeneric

func TransliterateGeneric(input string, b *strings.Builder)

transliterateGeneric handles basic Latin normalization.

func TransliterateRussian

func TransliterateRussian(input string, b *strings.Builder)

transliterateCyrillic handles Cyrillic script (Russian).

func TransliterateUnidecode

func TransliterateUnidecode(input string, b *strings.Builder)

transliterateUnidecode default (no dependency) version.

Types

type Cache

type Cache struct {
	Mu    sync.RWMutex
	Store map[string]struct{}
}

Cache is a simple in-memory store for slug uniqueness.

func (*Cache) Del

func (c *Cache) Del(slug string)

Del removes a slug from the cache.

func (*Cache) Get

func (c *Cache) Get(slug string) bool

Get checks if a slug object exist in the cache

func (*Cache) Set

func (c *Cache) Set(slug string)

Set adds a slug to the in-memory cache.

type Config

type Config struct {
	MaxLength     int                 // Maximum allowed length of the final slug (e.g., 220 characters)
	SuffixStyle   string              // Style of suffix: "numeric" (-2), "version" (-v2), "revision" (-rev2)
	Language      string              // Language will hold the preferred Language to transliteration Default: english
	RegexReplace  string              // Will hold the things that will be replaced
	StopWords     map[string]struct{} // All words that will be removed from the input if given
	Abbreviations map[string]string   // Abbreviations that will be removed from the input if given
	UseCache      bool                // Flag to enable in-memory caching of slug lookups
	ZeroAlloc     bool                // Controls zero-allocation mode
	UseUnidecode  bool                // Optional unidecode fallback
	Cache         *Cache              // In-memory cache struct
	RegexFilter   *regexp.Regexp      // Regex pattern to replace certain characters from input if given
	PipeLine      []Transformer       // Pipeline for step by step process
	Builder       strings.Builder     // Buffer for zero-allocation processing
}

Config is the main struct for generating slugs.

func New

func New(options ...Options) *Config

New creates a new Config with default settings and optional configurations.

func (*Config) EnsureUnique

func (cfg *Config) EnsureUnique(ctx context.Context, slug string) string

EnsureUnique ensures the slug is unique using the in-memory cache.

func (*Config) Make

func (cfg *Config) Make(ctx context.Context, input string) (string, error)

Make generates a slug from the input string with the configured options.

func (*Config) MakeBulk

func (cfg *Config) MakeBulk(ctx context.Context, inputs []string) ([]string, error)

MakeBulk generates slugs for multilple inputs.

func (*Config) Transliterate

func (cfg *Config) Transliterate(input string) (string, error)

Transliterate converts text to a Latin-based slug using language-specific rules

type Options

type Options func(*Config)

Option defines a functional option for configuring Config.

func WithAbbreviation

func WithAbbreviation(from, to string) Options

WithAbbreviation adds a custom abbreviation rule.

func WithLanguage

func WithLanguage(lang string) Options

WithLanguage sets the language for transliteration.

func WithMaxLength

func WithMaxLength(max int) Options

WithMaxLength sets the maximum length of the slug

func WithPipeline

func WithPipeline(transformers ...Transformer) Options

WithPipeline sets custom transformations for the slug generation pipeline.

func WithRegexFilter

func WithRegexFilter(pattern, replace string) Options

WithRegexFilter sets a regex pattern to filter characters

func WithStopWords

func WithStopWords(lang string) Options

WithStopWords sets stopwords to remove from the slug

func WithSuffixStyle

func WithSuffixStyle(style string) Options

WithSuffixStyle sets the style for suffix generation ("numeric", "version", "revision")

func WithUnidecode

func WithUnidecode(enabled bool) Options

WithUnidecode enables the unidecode fallback.

func WithUseCache

func WithUseCache(use bool) Options

WithUseCache enables or disables in-memory caching for uniqueness

func WithZeroAlloc

func WithZeroAlloc(enabled bool) Options

WithZeroAlloc enables/disables zero-allocation mode.

type Transformer

type Transformer func(*strings.Builder)

Transformer defines a function that transform a string in pipeline.

func Lowercase

func Lowercase() Transformer

Lowercase converts text to lowercase in-place.

func RemoveDiacritics

func RemoveDiacritics() Transformer

RemoveDiacritics removes diacritics using Unicode normalization.

func ReplaceSpaces

func ReplaceSpaces(delimeter string) Transformer

ReplaceSpaces replaces spaces with dashes.

func TrimDashes

func TrimDashes() Transformer

TrimDashes trims leading and trailing dashes.

Directories

Path Synopsis
cmd
slugcraft command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL