Documentation
¶
Overview ¶
Package slug generates unique URL-safe slugs backed by a Bun database.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Generate ¶
Generate creates a unique slug for the given table using a Bun database. The slug always carries a random suffix ("my-title-<16 chars>"), which makes it safe under concurrent calls with the same title.
Example ¶
Generate slugifies the title and appends a random suffix, retrying until the `slug` column of the given table has no collision.
package main
import (
"context"
"database/sql"
"fmt"
"strings"
"github.com/rahmadafandi/fibr/v2/slug"
"github.com/uptrace/bun"
"github.com/uptrace/bun/dialect/sqlitedialect"
"github.com/uptrace/bun/driver/sqliteshim"
)
func main() {
sqldb, err := sql.Open(sqliteshim.ShimName, "file::memory:?cache=shared")
if err != nil {
panic(err)
}
db := bun.NewDB(sqldb, sqlitedialect.New())
defer db.Close()
if _, err := db.Exec("CREATE TABLE articles (slug TEXT)"); err != nil {
panic(err)
}
s, err := slug.Generate(context.Background(), db, "articles", "Hello, World!")
if err != nil {
panic(err)
}
fmt.Println(strings.HasPrefix(s, "hello-world-"))
}
Output: true
func GenerateReadable ¶ added in v2.1.0
func GenerateReadable(ctx context.Context, db *bun.DB, tableName string, title string) (string, error)
GenerateReadable returns the plain slug for title ("my-title") when the table has no row with it yet, and falls back to Generate's suffixed form otherwise.
The check and your later insert are separate steps, so two concurrent calls with the same title can both get the plain slug. Keep a unique index on the slug column and, on a unique violation, retry with Generate.
Types ¶
This section is empty.