@@ -7,6 +7,7 @@ import (
77 "strconv"
88 "strings"
99 "time"
10+ "unicode/utf8"
1011
1112 "github.com/gin-gonic/gin"
1213 )
@@ -402,6 +403,22 @@ type sendMessageRequest struct {
402403 Body string `json:"body"`
403404 }
404405
406+// checkBody rejects empty bodies and ones over the size cap, replying with the
407+// reason. The composer has no copy of the cap, so the toast shows this message.
408+func checkBody(c *gin.Context, body string) bool {
409+ if body == "" {
410+ c.JSON(http.StatusBadRequest, gin.H{"error": "invalid message"})
411+ return false
412+ }
413+ if n := utf8.RuneCountInString(body); n > maxMessageLen {
414+ c.JSON(http.StatusRequestEntityTooLarge, gin.H{
415+ "error": fmt.Sprintf("message is too long: %d of %d characters", n, maxMessageLen),
416+ })
417+ return false
418+ }
419+ return true
420+}
421+
405422 func (s *Server) handleSendMessage(c *gin.Context) {
406423 channelID, err := strconv.ParseInt(c.Param("id"), 10, 64)
407424 if err != nil {
@@ -414,8 +431,7 @@ func (s *Server) handleSendMessage(c *gin.Context) {
414431 return
415432 }
416433 body := strings.TrimSpace(req.Body)
417- if body == "" || len(body) > maxMessageLen {
418- c.JSON(http.StatusBadRequest, gin.H{"error": "invalid message"})
434+ if !checkBody(c, body) {
419435 return
420436 }
421437 user := c.MustGet("user").(User)
@@ -450,8 +466,7 @@ func (s *Server) handleEditMessage(c *gin.Context) {
450466 return
451467 }
452468 body := strings.TrimSpace(req.Body)
453- if body == "" || len(body) > maxMessageLen {
454- c.JSON(http.StatusBadRequest, gin.H{"error": "invalid message"})
469+ if !checkBody(c, body) {
455470 return
456471 }
457472 user := c.MustGet("user").(User)