gosimple / slug

URL-friendly slugify with multiple languages support.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

IsSlug for empty string

xescugc opened this issue · comments

IDK exatly if it's a bug or it's supose to be this way really hehe.

package main

import (
        "fmt"

        "github.com/gosimple/slug"
)

func main() {
        text := ""
        fmt.Printf("IsSlug: %t\n", slug.IsSlug(text))
}

the output is:

IsSlug: true

IMO an empty string should not be considred a slug but before opening a PR I wanted to know if it should be 😄

Sorry for late reply, I was few days on vacations.

Thank you for report. From my point of view empty string is not slug. PR welcome.

Hmmm, this also got me thinking about MaxLength int.

slug/slug.go

Lines 23 to 29 in a1294ed

// MaxLength stores maximum slug length.
// It's smart so it will cat slug after full word.
// By default slugs aren't shortened.
// If MaxLength is smaller than length of the first word, then returned
// slug will contain only substring from the first word truncated
// after MaxLength.
MaxLength int

Maybe it should be uint, but that would be API change.
Or it should be checked if it's bigger than 0 in smartTruncate function

About the MaxLenght yes, I think as it represent a length, and it'll never be negative, it should be a uint but as you mention is a API change.

But all of this does not affect the IsSlug with empty strings, because it does not use the smartTruncate no? We could use the smartTruncate at the start of the IsSlug to maybe short the string or check the MaxLength to just say that it's not a valid slug as it is longer as defined.

Personally I would like to not use smartTruncate.
I thought about IsSlug as only checking of provided string if it not contain symbols from outside of ASCII range.
Shit, maybe it should also check if provided string have - or _ as prefix/sufix and return false in such cases...

Haha ok I'll do it 👍(the prefix/sufix - _) , I thought about using a regexp to validate the IsSlug instead of checking each character of the string, and also validate the length to the MaxLength.

I tried regexp first for IsSlug but it was like 100 times slower... You can check yourself, benchmarks are included:
https://github.com/gosimple/slug/blob/master/slug_test.go#L375-L407

Ok just tested the same code with just a regexp ^[a-z0-9]+(?:[a-z0-9_-]*[a-z0-9]+)?$ and it's still slow AF haha.

I'm going to open a PR with the fixes we discussed 👍

Thank you for report and fixes.