nicer file names for posts
This commit is contained in:
parent
bdb08657e3
commit
0a3af85b02
|
@ -3,6 +3,7 @@ package owl
|
|||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func dirExists(path string) bool {
|
||||
|
@ -38,3 +39,24 @@ func walkDir(path string) []string {
|
|||
})
|
||||
return files
|
||||
}
|
||||
|
||||
func toDirectoryName(name string) string {
|
||||
name = strings.ToLower(strings.ReplaceAll(name, " ", "-"))
|
||||
// remove all non-alphanumeric characters
|
||||
name = strings.Map(func(r rune) rune {
|
||||
if r >= 'a' && r <= 'z' {
|
||||
return r
|
||||
}
|
||||
if r >= 'A' && r <= 'Z' {
|
||||
return r
|
||||
}
|
||||
if r >= '0' && r <= '9' {
|
||||
return r
|
||||
}
|
||||
if r == '-' {
|
||||
return r
|
||||
}
|
||||
return -1
|
||||
}, name)
|
||||
return name
|
||||
}
|
||||
|
|
5
user.go
5
user.go
|
@ -142,8 +142,7 @@ func (user User) GetPost(id string) (Post, error) {
|
|||
}
|
||||
|
||||
func (user User) CreateNewPost(title string, draft bool) (Post, error) {
|
||||
timestamp := time.Now().UTC().Unix()
|
||||
folder_name := fmt.Sprintf("%d-%s", timestamp, title)
|
||||
folder_name := toDirectoryName(title)
|
||||
post_dir := path.Join(user.Dir(), "public", folder_name)
|
||||
|
||||
// if post already exists, add -n to the end of the name
|
||||
|
@ -151,7 +150,7 @@ func (user User) CreateNewPost(title string, draft bool) (Post, error) {
|
|||
for {
|
||||
if dirExists(post_dir) {
|
||||
i++
|
||||
folder_name = fmt.Sprintf("%d-%s-%d", timestamp, title, i)
|
||||
folder_name = toDirectoryName(fmt.Sprintf("%s-%d", title, i))
|
||||
post_dir = path.Join(user.Dir(), "public", folder_name)
|
||||
} else {
|
||||
break
|
||||
|
|
|
@ -317,3 +317,11 @@ func TestAvatarSetIfFileExist(t *testing.T) {
|
|||
t.Error("Avatar should not be empty")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostNameIllegalFileName(t *testing.T) {
|
||||
user := getTestUser()
|
||||
_, err := user.CreateNewPost("testpost?///", false)
|
||||
if err != nil {
|
||||
t.Error("Should not have failed")
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue