Prevent 500 errors on too-long collection title or description

This truncates long titles and descriptions to the maximum column length, so
we don't get errors back from MySQL.

Fixes #600
This commit is contained in:
Matt Baer 2023-10-03 11:55:52 -04:00
parent 7db4b699e2
commit 530a36fc53
3 changed files with 24 additions and 1 deletions

View File

@ -39,7 +39,12 @@ import (
"golang.org/x/net/idna"
)
const collAttrLetterReplyTo = "letter_reply_to"
const (
collAttrLetterReplyTo = "letter_reply_to"
collMaxLengthTitle = 255
collMaxLengthDescription = 160
)
type (
// TODO: add Direction to db

View File

@ -17,6 +17,7 @@ import (
"github.com/go-sql-driver/mysql"
"github.com/writeas/web-core/silobridge"
wf_db "github.com/writefreely/writefreely/db"
"github.com/writefreely/writefreely/parse"
"net/http"
"net/url"
"strings"
@ -862,6 +863,14 @@ func (db *datastore) GetCollectionFromDomain(host string) (*Collection, error) {
}
func (db *datastore) UpdateCollection(app *App, c *SubmittedCollection, alias string) error {
// Truncate fields correctly, so we don't get "Data too long for column" errors in MySQL (writefreely#600)
if c.Title != nil {
*c.Title = parse.Truncate(*c.Title, collMaxLengthTitle)
}
if c.Description != nil {
*c.Description = parse.Truncate(*c.Description, collMaxLengthDescription)
}
q := query.NewUpdate().
SetStringPtr(c.Title, "title").
SetStringPtr(c.Description, "description").

View File

@ -80,3 +80,12 @@ func TruncToWord(s string, l int) (string, bool) {
}
return s, truncated
}
// Truncate truncates the given text to the provided limit, returning the original string if it's shorter than the limit.
func Truncate(s string, l int) string {
c := []rune(s)
if len(c) > l {
s = string(c[:l])
}
return s
}